Angular Form 中 ngModel 的意外行为 [英] ngModel's unexpected behavior inside Angular Form
问题描述
以下代码将生成两个具有相同值bye
(而不是hello
和bye
)的inputs
.如果有人能够(理论上)解释这种行为并说出确切原因,那就太好了.
</表单>
为了更好地解释我的问题:
原因不可能是因为它们绑定到同一个对象,所以它们将具有相同的值.如果是这样,则以下情况对于两个输入将具有相同的值,这显然不是这种情况.
app.component.html
</表单>
app.component.ts
arr = [1,4]ngOnInit(){setTimeout(()=>{this.arr[1] = 5;});}
请注意:我想我已经正确解释了我的问题,以及为什么我认为@DeborahK 的解决方案似乎不适合我.我正在寻找这种行为的原因.而不是解决方法.另外,我知道在每个输入中更改 name
会使其正常工作.所以请停止建议.
Name 属性应该是唯一的
</表单>
The following code will generate two inputs
with same value bye
(instead of hello
and bye
). It would be great if someone could (theoretically) explain this behaviour and tell the exact cause.
<form>
<div *ngFor="let item of ['hello', 'bye'];">
<input name="name" [(ngModel)]="item">
</div>
</form>
Edit: To explain my question better:
The reason couldn't be that because they are bind to the same object, they will have identical value. If that is so the following case would have the same value for both of inputs, which is obviously not the case.
app.component.html
<form>
<div *ngFor="let item of arr;">
<input name="name" [(ngModel)]="item">
</div>
</form>
app.component.ts
arr = [1,4]
ngOnInit(){
setTimeout(()=>{
this.arr[1] = 5;
});
}
Please note: I think I have explained my question properly and also why I think @DeborahK's solution doesn't seem fit to me. I am looking for a reason for such behavior. And not the workaround. Also, I know that changing name
in each input would make it work fine. So please stop suggesting that.
Name attribute sould be unique
<form>
<div *ngFor="let item of ['hello', 'bye'];let i =index">
<input name="{{i}}" [(ngModel)]="item">
</div>
</form>
这篇关于Angular Form 中 ngModel 的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!