我正在尝试通过使用角度反应表单单击"+"来生成字段数组的表单。但是,当我尝试在子组件中使用[formControlName]="index"
时,它不起作用。
首先是说formControlName
应该有一个父母FormGroup
我通过了它并补充说。现在它说Cannot find control name with unspecified name attribute
.在Angular文档中,据说人们可以将FormArray与[formControlName]
和索引一起使用,因为没有名称。
这就是我所拥有的 https://stackblitz.com/edit/angular-runxfe
我已经解决了你的问题。您需要在此处传递表单组名称:
<app-site-form-feature
*ngFor="let feature of features.controls; let last = last; let index = index; let first = first" [formGroupName]="index"
[last]="last" [index]="index" [first]="first"
(addFeature)="addFeature()" (removeFeature)="removeFeature(index, first, last)">
</app-site-form-feature>
子组件的 HTML 将如下所示:
<div class="row no-gutters form-group">
<input type="text" class="form-control px-2 col-10">
<span class="btn btn-outline-danger" (click)="removeFeature.emit(index, first, last)">-</span>
<span class="btn btn-success" *ngIf="last" (click)="addFeature.emit($event,index)">+</span>
</div>
看看这个闪电战 https://stackblitz.com/edit/angular-v8zkz2
您还可以参考本指南: https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/