[英]angular2 capture info from dynamically generated inputs - possible?
Working on an update form which I would like to generate and capture inputs for a variable sized array 正在处理一个更新表单,我想为可变大小的数组生成和捕获输入
The current unhappy version only supports the first three statically defined elements in the constituency array. 当前不满意的版本仅支持选区数组中的前三个静态定义的元素。 So the inputs look like this... 所以输入看起来像这样...
<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]}}>
and the function to update pulls the values of the form using the static octothorpe tags. 更新功能使用静态octothorpe标签提取表单的值。
updateLegislator(newConstituency1.value, newConstituency2.value, newConstituency3.value)
But this doesn't allow for a variable sized Constituency array. 但是,这不允许使用可变大小的选区数组。
I am able to use *ngFor
directive to dynamically create input fields for a theoretically infinitely sized constituency array: 我可以使用*ngFor
指令为理论上无限大小的选区数组动态创建输入字段:
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}}>
</div>
but have not successfully been able to capture that information thereafter. 但此后未能成功捕获该信息。 Any kind assistance would be greatly appreciated. 任何帮助将不胜感激。
Use two-way data binding: 使用双向数据绑定:
<div *ngFor="constit of legislatorToDisplay?.constituency; let i = index">
<input [(ngModel)]="legislatorToDisplay?.constituency[i]">
</div>
You just have to have a form object in your component that matches the HTML input components that were created. 您只需在组件中具有一个与创建的HTML输入组件匹配的表单对象即可。
Template 模板
<div *ngfor constit of legislatorToDisplay?.constituency>
<input value={{constit}} formControlName="{{constit}}">
</div>
Component 零件
/* 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.