如何使用嵌套字段创建表单,我知道angular2 RC中的 formArray
但有点混淆如何正确使用它?假设我有一个这样的形式
// Main Form with formArray named as `global_modifier`
this.myForm = this._fb.group({
.......
name: ['', []],
global_modifier: this._fb.array([
this.initGlobalModifiers()
])
....
});
removeModifier(i: number) {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.removeAt(i);
}
addModifier() {
const control = <FormArray>this.myForm.controls['global_modifier'];
control.push(this.initGlobalModifiers());
}
/*global_modifier function having nested fields named `items` .....*/
initGlobalModifiers() {
return this._fb.group({
.....
modifier_title: ['', []],
items: this._fb.array([
this.initItems()
])
.........
});
}
removeItem(i: number) {
const control = <FormArray>this.myForm.controls['items'];
control.removeAt(i);
}
addItem() {
const control = <FormArray>this.myForm.controls['items'];
control.push(this.initItems());
}
// items intilization
initItems() {
return this._fb.group({
item_title: ['', []],
item_price: ['', []]
});
}
现在我很困惑如何在html中使用这个表单?
我正在尝试这个,但没有按预期工作..
<form [formGroup]="myForm" novalidate>
<input type="text" placeholder="name" formControlName="name" maxlength="50">
<div formArrayName="global_modifier" *ngFor="let cont of myForm.controls.global_modifier.controls; let i=index, let fst=first">
<div [formGroupName]="i">
<input type="text" placeholder="modifier_title" formControlName="modifier_title" maxlength="50">
<button *ngIf="fst" [ngClass]="{'inputAddButton ':fst}" (click)="addModifier(i)" type="button">
<i class="fa fa-plus fa-white" aria-hidden="true"></i>
</button>
<button *ngIf="!fst" [ngClass]="{'inputDeleteButton ':!fst}" (click)="removeModifier(i)">
<i class="fa fa-trash-o fa-white" aria-hidden="true"></i>
</button>
<!--block For form mlutiple entrys-------------------->
<div formArrayName="items">
<div *ngFor="let items of cont.items; let item_index=index, let fst=first">
<div [formGroupName]="i">
<div style="margin-bottom:10px">
............... NOTHING dISPLAY HERE ???
</div>
</div>
</div>
</div>
<!--block For form mlutiple entrys---=------------>
<br>
</div>
</div>
</form>
什么是我的代码中的错误?或者有任何人在angular2中有嵌套表格的例子吗?
2 回答
检查这个适用于我的示例,直到rc4(没有检查更新的版本):
表格标记
HTML标记
备注
this.myForm = this.formBuilder.group
使用用户的配置创建一个表单对象,并将其分配给this.myForm变量 .
'loginCredentials': this.formBuilder.group
方法创建一组控件,包括 formControlName 例如 .
login
和值['', Validators.required],
其中第一个参数是表单输入的初始值,secons是验证器或验证器数组,如'email': ['', [Validators.required, customValidator]],
.创建一个组数组,其中组的索引在数组中为 formGroupName ,并且访问方式如下:
此示例方法将新formGroup添加到数组中 . 当前访问需要指定我们想要访问的控件类型,在此示例中,此类型为:
<FormArray>
与上述相同的规则适用于从数组中删除特定的表单控件
Nested Form with nested ARRAY
Plunker:https://plnkr.co/edit/sUjE1ULYhfDHLNBw2sRv?p=info Scotch.IO:https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2
我认为你的错误在于
你应该推送你的Form / FormGroup对象不要控制 . 请参阅PLUNKER以查看工作示例 .
正确的添加方法:
Nested Form with nested OBJECTS
...