ngFor项目被追加而不是简单的更新

时间:2017-11-24 11:46:30

标签: javascript angular dom angular2-template ngfor

在我的Angular 4应用程序中,当我使用新值更新数组时,不是向我显示新值,而是将值附加到DOM。我以前曾经使用过一百万次,但从未遇到过如此奇怪的行为。

这是我的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循环在这个组件中!

1 个答案:

答案 0 :(得分:0)

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

this.branchEmployees = [];

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

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

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

相关问题