ngModel在Angular Form中的意外行为 [英] ngModel's unexpected behavior inside Angular Form

查看:77
本文介绍了ngModel在Angular Form中的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将生成两个具有相同值 bye (而不是 hello bye )的 input .如果有人能够(从理论上)解释这种行为并指出确切原因,那就太好了.

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>

为了更好地解释我的问题:

原因可能不是因为它们绑定到同一对象,所以它们将具有相同的值.如果是这样,则以下情况对于两个输入将具有相同的值,显然不是这种情况.

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;
    });
  }

请注意::我想我已经正确解释了我的问题,以及为什么我认为@DeborahK的解决方案似乎不适合我.我正在寻找这种行为的原因.而不是解决方法.另外,我知道在每个输入中更改 name 可以使其正常工作.因此,请不要再建议这一点.

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.

推荐答案

名称属性应唯一

 <form>
      <div *ngFor="let item of ['hello', 'bye'];let i =index">
        <input  name="{{i}}" [(ngModel)]="item">
      </div>
    </form>

这篇关于ngModel在Angular Form中的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆