Angular官方文档中的示例显示以下代码:
@Component({
template: `
<form [formGroup]="form">
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i">
</div>
</div>
</form>
`,
})
export class NestedFormArray {
form = new FormGroup({
cities: new FormArray([
new FormControl('SF'),
new FormControl('NY'),
]),
});
get cities(): FormArray { return this.form.get('cities') as FormArray; }
}
即使在没有代码的情况下,我也无法理解为什么我们需要formArrayName指令?
<form [formGroup]="form">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i">
</div>
</form>
答案 0 :(得分:0)
<form [formGroup]="form">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i">
</div>
</form>
没有FormArrayName不能用于以下结构:
new FormGroup({
cities: new FormArray([
new FormControl('SF'),
new FormControl('NY'),
]),
});
<input [formControlName]="i">
-介绍如何将FormControl(input)同步到现有的<form [formGroup]="form">
。
因此它适用于该结构:
new FormArray([
new FormControl('SF'),
new FormControl('NY'),
]);