【问题标题】:ngFor items getting appended instead of simple updatingngFor 项目被追加而不是简单的更新
【发布时间】:2018-05-08 10:22:33
【问题描述】:

在我的 Angular 4 应用程序中,当我使用新值更新数组时,这些值不会显示新值,而是附加到 DOM。我之前使用过 ngFor 一百万次,但从未遇到过这种奇怪的行为。

这是我的html

<div class="roles-list" *ngIf="branchEmployees && branchEmployees.length > 0">
          <div class="roles-item" *ngFor="let branchEmployee of branchEmployees">
            <div class="branch-image" [ngStyle]="{'background-image': 'url(' + branchEmployee.branch.organisation.profile_photo_urls.thumb + ')'}">
            </div>
            <div class="branch-name">
              {{ branchEmployee.branch.name }}
            </div>
            <div class="branch-employee-role">
              <select (change)="employeeRoleChange($event.target.value, branchEmployee.id)" [(ngModel)]="branchEmployee.access_type">
                <option value="user">{{'User'}}</option>
                <option value="admin">{{'Admin'}}</option>
              </select>
            </div>
          </div>
        </div>

这是我的组件

this.branchEmployees = [];
this.model.get({name: `people/${this.selectedEmployee.person.id}/branch_employees`}).subscribe(branchEmployees => {
  this.branchEmployees = branchEmployees
})

组件中的上述代码在单击某个按钮时运行。 我可以验证变量 this.branchEmployees 具有正确数量的值,但不知何故,这些值没有在 DOM 中被替换而是被附加,而且这种行为不仅适用于这个 ngFor,它适用于这个组件中的每个 ngFor 循环!

【问题讨论】:

  • branchEmployee 是什么样的?他们有唯一的 id 吗?
  • 是的,它们有 uni id,但这并不重要,因为它包含什么,因为归根结底,它是数组中的一项
  • 我想我误解了你的问题。 *ngFor 不这样做。如果您不想渲染元素,则​​需要将它们从branchEmployees 中删除。如果您总是添加,*ngFor 将始终添加。
  • 查看组件中的代码,我正在清空数组以确定,然后放入新值。现在假设我的数组包含以前的 2 个值,现在我清空它们,添加新值(比如说 4)现在 this.branchEmployees 有 4 个值但是在 dom 中,有 6 个值,2 个以前的和 4 个新的
  • 我假设 model.get() 保留旧值,this.branchEmployees = branchEmployees 是一个不断增长的数组。我可以确保你 *ngFor 本身不会那样做。

标签: javascript angular dom angular2-template ngfor


【解决方案1】:

在您的问题中编写代码的更好方法是移动

this.branchEmployees = [];

在异步调用的回调函数里面,像这样:

    this.model.get({name: `people/${this.selectedEmployee.person.id}/branch_employees`}).subscribe(branchEmployees => {
      this.branchEmployees = [];
      this.branchEmployees = branchEmployees
    })

一方面,它会在获取新数据时刷新列表中的数据,并且 即使呼叫在网络上失败/延迟(服务或服务器或某些其他资源不可用或损坏),您也能够保留/绘制列表中的数据branchEmployees

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2016-09-23
    • 2019-05-22
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2015-09-04
    相关资源
    最近更新 更多