【问题标题】:Angular - inputs created by *ngFor causes duplicate values to display when blur event firesAngular - 由 *ngFor 创建的输入会导致在触发模糊事件时显示重复值
【发布时间】:2019-02-17 11:32:29
【问题描述】:

当用户在输入和选项卡中输入数据时,模糊事件会更新 *ngFor 中使用的底层数组(1 个值)。然而,DOM 显示 2 个重复值。

查看 stackblitz 以获取显示问题的工作代码: https://stackblitz.com/github/mpierce5/duplication-error/tree/master

【问题讨论】:

  • 使用对象而不是array of string。您也不需要(blur) 事件,只需使用ngModel 提供的绑定角度即可

标签: angular ngfor onblur


【解决方案1】:

正如@penleychan 所说,当您需要更改 ngFor 使用的项目时,请使用对象。我的意思是这样声明你的模型:

this.testList = [
      { value: '-- placeholder --' },
      { value: '-- placeholder --' },
      { value: '-- placeholder --' },
      { value: '-- placeholder --' },
    ];

然后像这样绑定到它:

  <input
    *ngFor="let testUnit of testList; let i = index"
    (blur)="editItem($event.target.value, i)"
    class="test-input"
    placeholder="Change Me"
    [attr.value]="testUnit.value == '-- placeholder --' ? '': testUnit.value">


  <div class="test-value-area">
    <div class="test-value-area-title">Array Values</div>
    <p *ngFor="let testUnit of testList">{{testUnit.value}}</p>
  </div>

欲了解更多信息,请参阅here

【讨论】:

  • 对此进行了测试,它确实有效,我确实必须更新 cmelee 提到的 editItem()。这是一个有效解决方案的链接。link 谢谢!
【解决方案2】:

很好的答案 Fartab。我只会再添加一件事,也更新 editItem 方法:

public editItem(value, index: number) {
    this.testList[index] = {"value": value};
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多