在嵌套表单中,当尝试从空值(null)中读取控件属性时会引发此错误。为了解决此问题,需要自定义验证器(custom validator),并在该验证器中进行空值检查。以下示例代码演示如何创建一个自定义验证器以检查空值:
export function nonNull(control: FormControl) {
return control.value !== null ? null : { nonNull: true };
}
在嵌套表单中使用此自定义验证器:
this.form = this.fb.group({
nestedForm: this.fb.group({
someControl: [null, nonNull] // 使用自定义验证器
})
});
此时,当尝试从空值中读取控件属性时,将会使用自定义验证器进行检查,从而避免出现“Cannot read properties of null (reading 'controls')”错误。