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

Discussão em 'Angular' iniciado por Martin Carre, Maio 7, 2025.

  1. Martin Carre

    Martin Carre Guest

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

    Continue reading...

Compartilhe esta Página