-1

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 = {};
0

1 Answer 1

1

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

1
  • I've tried it and for some reason it's still complaining... no matter if it's an if statement, the "?" or the a controversial "!" nothing will do. The solution I found, which I hate, is to specify (field: any) instead of (field: FormlyFieldConfig)... Sep 14 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.