【发布时间】: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