这个错误发生在我们尝试从表单控件中访问 control.controls 属性时。这是因为 AbstractControl 类型不包含 controls 属性。
为了避免这个错误,在访问 controls 属性之前,我们需要检查该控件是否为 FormGroup 类型。只有 FormGroup 类型才有 controls 属性。可以使用类型断言来实现:
例如,我们有以下表单:
myForm = new FormGroup({ name: new FormControl(), address: new FormGroup({ street: new FormControl(), city: new FormControl(), state: new FormControl() }) });
当我们需要访问 address 控件的 controls 属性时,需要对其进行类型转换:
const addressControl = this.myForm.get('address'); if (addressControl instanceof FormGroup) { const cityControl = addressControl.get('city'); console.log(cityControl.value); }
这样就可以避免出现“Property 'controls' does not exist on type 'AbstractControl'”错误了。