动态添加输入字段时遇到问题,
当我单击加号按钮时,它将调用AddItemData(),但此函数未将新的输入字段添加到deck_array
这是我的代码,
home.html
<form [formGroup]="myForm1">
<ion-list no-lines class="listMargin">
<ion-item>
<ion-label class="labelColor" stacked>
Ship name
</ion-label>
<ion-input formControlName="ship_name" type="text"></ion-input>
</ion-item>
<div formArrayName="deck_array" style="background-color:white">
<ion-list *ngFor="let obj of myForm1.controls.deck_array.controls;let i=index">
<div>
<ion-item no-lines>
<ion-input [formControlName]="i" placeholder="select from list or type in"></ion-input>
</ion-item>
</div>
</ion-list>
</div>
</ion-list>
<ion-item style="background-color: transparent">
<button item-start ion-fab mini color="dark" (click)="AddItemData('')">
Add New field
<ion-icon name="add"></ion-icon>
</button>
</ion-item>
</form>
我收到的来自服务器的响应以 pData 格式,请考虑以下格式
home.ts
constructor(private _fb: FormBuilder) {}
ngOnInit() {
this.pData = {
"ship_name": "Abit smith",
"deck_array": [
"MD 1",
"MD 2"
],
};
this.myForm1 = this._fb.group({
ship_name: [this.pData.ship_name],
deck_array: this._fb.array([])
});
this.AddItemData(this.pData.deck_array);
console.log(this.myForm1.value);
}
AddItemData(item) {
const arrayControl = ( < FormArray > this.myForm1.get('deck_array'));
const controls = item.map(value => this._fb.control(value));
controls.forEach(control => arrayControl.push(control));
}
为什么没有添加,有人可以帮助我吗?
谢谢!
答案 0 :(得分:1)
模板:
<button item-start ion-fab mini color="dark" (click)="addItem()">
Add New field
<ion-icon name="add"></ion-icon>
</button>
TypeScript:
addItem() {
(<FormArray>this.myForm1.get('deck_array')).push(this._fb.control(''));
}