* ng关于如何使用索引将数组中的每个项目绑定到ngModel [英] *ngFor how to bind each item in array to ngModel using index
问题描述
===最终更新==
===final updated==
http://plnkr.co/edit/WKRBB7?p=preview
由于我以某种形式使用ngModel,因此必须添加name
属性.
since I use ngModel in a form, I must add name
attribue.
我的错误是我使用了与其名称相同的值.
and my mistake is that I used same value as its name.
<form #myform="ngForm">
<table>
<tr *ngFor="let staff of staffs">
<td><input name="name" [(ngModel)]="staff.name">{{staff.name}}</td>
</tr>
</table>
</form>
更改为以下内容后,我的问题已解决.
after I change to belows, my problem is resolved.
<form #my2form="ngForm">
<table>
<tr *ngFor="let staff of staffs;let i = index">
<td><input name="staff.{{i}}.name" [(ngModel)]="staff.name">{{staff.name}}</td>
</tr>
</table>
</form>
==========
==========
对不起,我不记得为什么我使用名称[$ index] .Name而不是x.Name.
sorry, I can't remember why I use names[$index].Name instead of x.Name.
也许几年前,我使用x.Name遇到了一些错误,然后养成了使用索引的习惯.
maybe years ago I meet some mistake using x.Name, and then made a habit of using index.
-更新------
我需要一个内联编辑表,双向绑定.
I need a inline edit table, two-way binding.
<table>
<tr *ngFor="let x of names">
<td><input [(ngModel)]="x.Name">{{x.Name}}</td>
</tr>
</table>
let names = [
{ Name:'jim'},
{ Name:'tom'}
];
页面最初显示:
blank text field; jim
blank text field; tom
在第一个文本字段中输入"aaaaaa"后,它变为:
after I type 'aaaaaa' in the first text field, it becomes:
aaaaaa; aaaaaa
blank text field; tom
我认为页面最初会显示:
I think the page initially would show:
jim; jim
tom; tom
那么,我的问题恰恰是为什么缺少初始值?
so, my problem exactly is, why the initial value is missing?
推荐答案
应为[ngModel]="..."
<table>
<tr *ngFor="let x of names;let i = index;">
<td>{{ i+ 1 }}</td>
<td><input [(ngModel)]="names[i].Name">{{x.Name}}</td>
</tr>
</table>
这篇关于* ng关于如何使用索引将数组中的每个项目绑定到ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!