我正在为其中一个项目使用反应形式数组。我正在尝试制作一个动态表单,该表单在单击按钮时添加/删除字段。我的代码中出现以下错误
错误错误:formArrayName必须与父formGroup指令一起使用。您将要添加一个formGroup 指令并将其传递给现有的FormGroup实例
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
public communicationForm: FormGroup;
public items: FormArray;
createItem(): FormGroup {
return this.fb.group({
communicationType: [''],
communicationValue: ['']
});
}
addItem(): void {
// this.items = this.communicationForm.get('items') as FormArray;
this.items.push(this.createItem());
}
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.communicationForm = this.fb.group({
items: this.fb.array([this.createItem()])
}),
this.items = this.communicationForm.get('items') as FormArray;
}
<div class="col-md-6">
<h3>Communications</h3>
<div formArrayName="items" *ngFor="let item of communicationForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<select class="form-group col-md-5" (change)="changeCommunication($event)" formControlName="communicationType">
<option value="" disabled>Communications</option>
<option *ngFor="let communication of Communications" [ngValue]="communication.id">
{{communication.name}}
</option>
</select>
</div>
<div [formGroupName]="i">
<input type="text" class="col-md-6" formControlName="communicationValue">
</div>
<div [formGroupName]="i">
<i class="fa fa-plus-circle" (click)="addItem()"></i>
</div>
</div>
</div>
答案 0 :(得分:2)
添加父formGroup:
<div class="col-md-6" [formGroup]="communicationForm">
我唯一要更改的是为项目添加吸气剂:
TS
get items(): FormArray {
return this.communicationForm.get('items') as FormArray;
}
ngOnInit是:
ngOnInit() {
this.communicationForm = this.fb.group({
items: this.fb.array([this.createItem()])
})
}
HTML
<div class="col-md-6">
<h3>Communications</h3>
<div formArrayName="items" *ngFor="let item of items.controls; let i = index;">
<div [formGroupName]="i">
<select class="form-group col-md-5" (change)="changeCommunication($event)" formControlName="communicationType">
<option value="" disabled>Communications</option>
<option *ngFor="let communication of Communications" [ngValue]="communication.id">
{{communication.name}}
</option>
</select>
</div>
<div [formGroupName]="i">
<input type="text" class="col-md-6" formControlName="communicationValue">
</div>
<div>
<i class="fa fa-plus-circle" (click)="addItem()"></i>
</div>
</div>
</div>
答案 1 :(得分:0)
当我们使用的formGroup中没有关闭FormArray时
<form [formGroup]="items">
<!--see that iterate over items.controls-->
<!-- and create a formGroup= the variable -->
<div *ngFor="let group of items.controls" [formGroup]="group">
<input formControlName="communicationType">
<input formControlName="communicationValue">
</div>
</form>