我对嵌套模型驱动表单没有太多经验,但我找到了一些资源。
这是一个例子的肉和土豆:
<div formArrayName="addresses">
<div *ngFor="let address of myForm.controls.addresses.controls; let i=index" class="panel panel-default">
<div class="panel-heading">
<span>Address {{i + 1}}</span>
<span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addresses.controls.length > 1" (click)="removeAddress(i)"></span>
</div>
<div class="panel-body" [formGroupName]="i">
<div class="form-group col-xs-6">
<label>street</label>
<input type="text" class="form-control" formControlName="street">
<small [hidden]="myForm.controls.addresses.controls[i].controls.street.valid" class="text-danger">
Street is required
</small>
</div>
<div class="form-group col-xs-6">
<label>postcode</label>
<input type="text" class="form-control" formControlName="postcode">
</div>
</div>
</div>
</div>
和控制器:
public myForm: FormGroup;
constructor(private _fb: FormBuilder) { }
ngOnInit() {
this.myForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(5)]],
addresses: this._fb.array([
this.initAddress(),
])
});
}
initAddress() {
return this._fb.group({
street: ['', Validators.required],
postcode: ['']
});
}
addAddress() {
const control = <FormArray>this.myForm.controls['addresses'];
control.push(this.initAddress());
}
removeAddress(i: number) {
const control = <FormArray>this.myForm.controls['addresses'];
control.removeAt(i);
}
plnkr 工作相对复杂的表格,来自这里。
我也想看看你的组件/控制器