Angular Formly Form hook OnInit -> field.xxx is possibly undefined

310 Views Asked by At

Angular version: 16.0 Formly version: 6.1.8

I'd need to create a cascated select for my app. The first field is a Material Autocomplete and then the next one a simple select I'm struggling, however, using hooks because field.parent appears to be possibly undefined:

(property) FormlyFieldConfig<FormlyFieldProps & { [additionalProperties: string]: any; }>.parent?: FormlyFieldConfig<FormlyFieldProps & {
    [additionalProperties: string]: any;
}> | undefined

So TypeScript is complaining when I try to access the previous field:

'field.parent' is possibly 'undefined'.ts(18048)
Cannot invoke an object which is possibly 'undefined'.ts(2722)

I'm confused about what I'm doing wrong in my context to have this object that's potentially "undefined".

form = new FormGroup({});
  sendForm: FormlyFieldConfig[] = [
    {
      key: 'thirdParty',
      type: 'autocomplete',
      props: {
        createLink: '/third-parties/create-thirdparty',
        required: true,
        label: 'Tercero',
        displayProp: 'displayName',
        valueProp: 'id',
        placeholder: 'Empresa XYZ',
        filter: (term: string) => {
          return this.thirdParties.asObservable().pipe(
            map(thirdParties => term ? this.filterThirdParties(term, thirdParties) : thirdParties)
        )},
      },
    },
    {
      key: 'user',
      type: 'select',
      props: {
        label: 'Usuario',
        options: [],
        required: true,
      },
      hooks: {
        onInit: (field: FormlyFieldConfig) => {
          const thirdParty = field.parent.get('thirdParty'); // <---- Here's the problem. 
        }
      },
      expressions: {
        hide: '!model.thirdParty',
      }
    }
  ];
  model = null;
  options: FormlyFormOptions = {};
1

There are 1 best solutions below

1
Matthieu Riegler On

field.parent is possibly undefined, use a Optional chaining operator (.?) to call the method. field.parent?.get('thirdParty')