我有一个分散在各个组件之间的表单,因此我需要使用.addControl
才能使表单一起工作。
这是当前的表单结构:
name: ['', [Validators.required, Validators.maxLength(255)]],
address: this.ofb.group({
addressLineOne: ['', Validators.required],
addressLineTwo: ['', Validators.required],
addressLineThree: [''],
addressPostcode: ['', [Validators.required, OrgValidators.postcodeValidator]]
})
我已将字段转换为.addControl
语法,如下所示:
this.createOrganisationForm.addControl('name', new FormControl(null, [Validators.required, Validators.maxLength(255)]));
this.createOrganisationForm.addControl('addressLineOne', new FormControl(null, [Validators.required]));
this.createOrganisationForm.addControl('addressLineTwo', new FormControl(null, [Validators.required]));
this.createOrganisationForm.addControl('addressLineThree', new FormControl(null, [Validators.required]));
this.createOrganisationForm.addControl('addressPostcode', new FormControl(null, [Validators.required, OrgValidators.postcodeValidator]));
但是,他们似乎丢失了组“地址”。我尝试将地址添加到这样的对象中:
let addressGroup = {
addressLineOne: ['', Validators.required],
addressLineTwo: ['', Validators.required],
addressLineThree: [''],
addressPostcode: ['', [Validators.required, OrgValidators.postcodeValidator]]
}
,然后像这样添加它:
this.createOrganisationForm.addControl('address', addressGroup);
但是我得到了错误:
不可分配给'AbstractControl'类型的参数。
如何使用.addControl
方法将一组控件添加到父控件。
谢谢
答案 0 :(得分:0)
如下所述,使用类型FormGroup
初始化您的addressGroup:
let addressGroup = {
let addressGroup: FormGroup = new FormGroup({
答案 1 :(得分:0)
这是因为addressGroup对象不是FormGroup类的实例。
const addressGroup = new FormGroup({
addressLineOne: ['', Validators.required],
....
})