【发布时间】:2018-11-15 20:09:36
【问题描述】:
目前我在 Angular 2 的一个项目中工作。我必须这样做。 简而言之,来自数据库的字段数据很少(字段值为“test8”的行)。之后,如果用户想要添加新的字段和值,那么他们必须单击“添加新行”按钮并使用提交按钮保存数据。 我的问题是我无法将用户提供的动态数据绑定到组件并将其保存在数据库中。
模板文件代码如下:
<form class="form-inline" role="form" id="SeasonAddForm" #userlogin = "ngForm" (ngSubmit)="updateBrochurePriceHandler()">
<div class="secondListDiv">
<div class="row " *ngFor="let sl of secondResultList, let index = index;">
<div class="col-xs-4">
<input id="branch_text_second{{index}}" name="saveData2-{{index}}-branch_text" class="form-control rt no-radius" type="text" value="{{sl.branch_text}}" [(ngModel)]="sl.branch_text" placeholder="">
</div>
<div class="col-xs-4">
<input id="initial_service_second{{index}}" name="saveData2-{{index}}-initial_service" class="form-control rt no-radius" type="text" value="{{sl.initial_service}}" [(ngModel)]="sl.initial_service" placeholder="">
</div>
<div class="col-xs-4">
<input id="quarterly_charge_second{{index}}" name="saveData2-{{index}}-quarterly_charge" class="form-control rt no-radius" type="text" value="{{sl.quarterly_charge}}" [(ngModel)]="sl.quarterly_charge" placeholder="">
</div>
<input id="type{{index}}" name="saveData2-{{index}}-type" class="form-control rt no-radius" type="hidden" value="{{sl.type}}" [(ngModel)]="sl.type" placeholder="">
</div>
</div>
<div class="row">
<div class="col-xs-4">
<input type="button" value="Add New Row" (click)="addSecondListRow()" class="frm_sub" id='addNewSecondDiv' >
</div>
</div>
</form>
组件文件代码在这里
public firstResultList:any;
public secondResultList:any;
private newFirstAttribute: any = {};
private newSecondAttribute: any = {};
addSecondListRow(){
this.newSecondAttribute.branch_text='';
this.newSecondAttribute.initial_service='';
this.newSecondAttribute.quarterly_charge='';
this.newSecondAttribute.type='2';
this.secondResultList.push(this.newSecondAttribute);
}
updateBrochurePriceHandler(formData) {
this.http.post(CONSTANTS.baseApiUrl +
'Angular2_api/update_brochure_price', formData)
.map(res => res.json())
.subscribe((data) => {
console.log(data);
})
}
【问题讨论】:
-
我建议你看一下关于form arrays in reactive forms的文档
-
您不能通过模板驱动的方法来做到这一点。您需要使用响应式表单数组来执行此操作。
-
但是我这里没有使用 ReactiveForm。我只使用了 ngForm。 @AndrewJuniorHoward
-
那我试试reactiveForm。 @trichetriche
-
@AndrewJuniorHoward 可以为此使用模板驱动的表单方法。但是使用响应式表单更容易(对我来说)而且做起来更快。