【发布时间】:2021-09-10 23:23:43
【问题描述】:
假设我有一个实现 CVA(控制值访问器)的嵌套表单。
// Child component which implements CVA
this.addressForm = new FormGroup({
city: new FormControl()
postalCode: new FormControl(null)
})
// Parent component html
<form [formGroup]= "productForm">
<input formControlName="date">
<address-form formControlName="addressForm"> </address-form>
</form>
// Parent component ts
this.productForm = new FormGroup({
date: new FormControl(null),
addressForm: new FormControl(null)
});
现在我只想修补 addresForm 的 city 字段,所以我尝试了:
// This will set other values of addressForm to null.
this.productForm.get('addressForm').patchValue({city: 'some-city'});
// This below will not work.
this.productForm.get('addressForm.city').patchValue('some-city');// error no city control.
// Another workaround is using ControlContainer instead to link to parent
Instead of this:
// this.addressForm = new FormGroup({
// city: new FormControl()
// postalCode: new FormControl(null)
//})
using this on child
this.addressForm = this.controlContainer.control as FormGroup;
and declare formGroup on Parent.
this.productForm = new FormGroup({
date: new FormControl(null),
addressForm: new FormGroup({city: new FormControl(null), postalCode: new FormControl(null) })
});
BUT in this workaround, writeValue method is not called on Child.
因为它是 formControlName 保存单个值,其他值被重置。 那么如何在不重置其他字段值的情况下设置嵌套表单字段值呢?
换句话说,我们如何控制来自父级的嵌套表单组件字段,例如修补值或监听特定字段值的变化? Stackblitz URL
【问题讨论】:
-
能否展示writeValue函数代码?
-
确定。这里控制台日志现在显示。公共 writeValue(value: TAddressForm): void { console.log('writeValue', value);常量 { 城市,邮政编码} = 价值 || {}; this.formGroup.patchValue({ city, postalCode}, { emitEvent: false }); }
-
问题是你正在解构 writeValue 参数,当你从发送对象 { city: 'some-city' } 的父级修补值时,JS 在这里找不到 postalCode 并将其设置为 undefined ,所以尝试这样做: public writeValue(value: TAddressForm): void { this.formGroup.patchValue(value || {}, { emitEvent: false }); } 和来自父母的: this.productForm.get('addressForm').patchValue({city: 'some-city'});
-
很遗憾不是这样,我在这个方法里面调用了console.log('writeValue),在devtools上看不到。
-
正如我告诉你的,将 writeValue 修补函数更改为 this.addressForm.patchValue(value || {});并且您的表单将正确修补:) stackblitz.com/edit/angular-we8nru 这是我的示例,我也为您准备了
标签: angular angular-reactive-forms angular-forms