我正在尝试按照this博客文章(方法1)实现一个子表单示例。在博客文章中,还有一个 stackblitz 示例。该示例使用角度 10,我使用角度 16。
场景如下。
我有这个简单的表格:
profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
aliases: this.fb.array([this.fb.control('')]),
});
在另一个组件中,我通过
Input@
将此表单作为父表单传递,并向其添加 address
组:
this.parentFormGroup.addControl(
'address',
this.fb.group({
street: ['', Validators.required],
city: [''],
state: [''],
zip: [''],
})
);
这个方法有效。显示子表单的控件,验证也有效。
现在,在主表单组件(
profileForm
所在的位置)中,我想修补这个address
表单组。
在博客文章中,这只需通过
patchValue
: 即可完成
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street',
},
});
}
在博客文章示例中,这是可行的。我认为,因为它使用角度 10。但在角度 16 中我收到错误:
Object literal may only specify known properties, and 'address' does not exist in type 'Partial<{ firstName: string | null; lastName: string | null; aliases: (string | null)[]; }>'
.
当然没有
address
属性。它是在运行时添加的。
但我能做到:
this.profileForm.patchValue({ firstName: 'Nancy' });
(this.profileForm.get('address') as any as FormGroup)?.patchValue({
street: '123 Drew Street',
});
它有效,但对我来说,这种双重演员有点尴尬。
是否真的没有其他方法可以做到这一点,而不在
address
上声明 profileForm
表单组?
终于找到了一个方便的方法:
(this.profileForm as FormGroup).patchValue({
firstName: 'Nancy',
address: { street: '123 Drew Street' },
});
通过将
profileForm
转换为 FormGroup
,它会变成通用表单组,并且不关心缺少的 address
属性。