[英]angular2 capture info from dynamically generated inputs - possible?
正在處理一個更新表單,我想為可變大小的數組生成和捕獲輸入
當前不滿意的版本僅支持選區數組中的前三個靜態定義的元素。 所以輸入看起來像這樣...
<input #newConstituency1 class="form-control" value={{legislatorToDisplay?.constituency[0]}}>
<input #newConstituency2 class="form-control" value={{legislatorToDisplay?.constituency[1]}}>
<input #newConstituency3 class="form-control" value={{legislatorToDisplay?.constituency[2]}}>
更新功能使用靜態octothorpe標簽提取表單的值。
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
但是,這不允許使用可變大小的選區數組。
我可以使用*ngFor
指令為理論上無限大小的選區數組動態創建輸入字段:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
但此后未能成功捕獲該信息。 任何幫助將不勝感激。
使用雙向數據綁定:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>
您只需在組件中具有一個與創建的HTML輸入組件匹配的表單對象即可。
模板
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
零件
/* create an empty form then loop through values and add control
fb is a FormBuilder object. */
let form = this.fb.group({});
for(let const of legislatorToDisplay.constituency) {
form.addControl(new FormControl(const))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.