[英]How can I add formArray to a formGroup?
first of all apologize for my English. 首先为我的英语道歉。
I have a problem when trying to add an array field to a formGroup. 尝试将数组字段添加到formGroup时遇到问题。
I'm trying to add a formArray using the push method to my rate formGroup, and the error I have I think is due to the formControlName. 我正在尝试使用push方法将formArray添加到我的速率formGroup中,我认为该错误是由于formControlName引起的。
As I searched and read the problem it is there, but I can not solve it, can someone help me please? 当我搜索并阅读问题时,它在那里,但是我无法解决,有人可以帮助我吗?
I created this stackblitz so you can see the error it gives me. 我创建了这个stackblitz,以便您可以看到它给我的错误。
https://stackblitz.com/edit/angular-mlk2mh https://stackblitz.com/edit/angular-mlk2mh
To work with FormArray you need to understand this: 要使用FormArray,您需要了解以下内容:
Need form group
\/\/\/
<form [formGroup]="rates">
<input type="text" placeholder="credit_card" formControlName="credit_card" />
Need form array name
\/\/\/
<div formArrayName="servicesRates" *ngFor="let item of rates.get('servicesRates').controls; let i = index;">
<div [formGroupName]="i"> <-- this is important
<input type="text" placeholder="id" formControlName="id" />
<input type="text" placeholder="Servicio" formControlName="service" />
<input type="text" placeholder="Price" formControlName="price" />
</div>
</div>
</form>
To work above HTML your TS must be: 要在HTML之上工作,您的TS必须为:
rates: FormGroup;
servicesRates: FormArray;
this.rates = this._formBuilder.group({
credit_card: [null, Validators.compose([Validators.required, Validators.minLength(8)])],
servicesRates: this._formBuilder.array([
this._formBuilder.group({
id: 0,
service: '',
price: 0,
})
])
});
and addNew function: 和addNew函数:
addField() {
this.servicesRates = this.rates.get('servicesRates') as FormArray;
this.servicesRates.push(this.servicesRates);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.