问题描述
对于来自 ngFor
的值,是否无法(或者不可能)使用 ngModel
? Angular是否试图保护我免受糟糕表现的影响?
Is it not possible (or not yet possible) to use ngModel
against values from ngFor
? Is Angular trying to protect me from bad performance?
效果很好:
<input type="text" [(ng-model)]="value">{{value}}
效果不是很好:
<li *ng-for="#name of names">
<input type="text" [(ng-model)]="name">{{name}}
</li>
我也尝试绑定到数组,其中......有点工作,但劫持焦点并引发异常:
I tried binding to the array as well, which... kind of works, but hijacks focus and also throws an exception: http://jsfiddle.net/langdonx/n5pjgev6/2/
<li *ng-for="#name of names; #i = index">
<input type="text" [(ng-model)]="names[i]">{{name}}
</li>
修改:
我可以绕过 LifeCycle.tick
使用更直接的方法问题,但焦点仍然被盗,因为 ngFor
重绘东西:
I can get around the LifeCycle.tick
issue using a more direct approach, but the focus is still stolen because ngFor
redraws things: http://jsfiddle.net/langdonx/n5pjgev6/3/
<li *ng-for="#name of names; #i = index">
<input type="text" [value]="names[i]" (input)="names[i] = $event.target.value">{{names[i]}}
</li>
推荐答案
我认为 ngFor
不喜欢跟踪具有 ngModel
的原始值的数组元素。
I think ngFor
don't like tracking array elements which are primitive values having ngModel
on them.
如果你在循环中移除了 ngModel
,它可以工作。
If you remove the ngModel
inside the loop, it works.
当我:
this.names = [{name: 'John'}, {name: 'Joe'}, {name: 'Jeff'}, {name: 'Jorge'}];
和
<li *ng-for="#n of names"><input type="text" [(ng-model)]="n.name">{{n.name}}</li>
这篇关于针对ngFor变量的Angular2 ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!