角度版本:16.0 正式版本:6.1.8
我需要为我的应用程序创建一个级联选择。第一个字段是材质自动完成,然后下一个字段是简单的选择 然而,我正在努力使用钩子,因为 field.parent 似乎可能未定义:
(property) FormlyFieldConfig<FormlyFieldProps & { [additionalProperties: string]: any; }>.parent?: FormlyFieldConfig<FormlyFieldProps & {
[additionalProperties: string]: any;
}> | undefined
所以当我尝试访问前一个字段时,TypeScript 会抱怨:
'field.parent' is possibly 'undefined'.ts(18048)
Cannot invoke an object which is possibly 'undefined'.ts(2722)
我对在我的上下文中做错了什么而让这个对象可能是“未定义”感到困惑。
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 = {};
field.parent
可能是 undefined
,请使用可选链接运算符 (.?
) 来调用该方法。 field.parent?.get('thirdParty')