我正在使用NGRX将数据从远程API加载到一个数组中,然后将该数组呈现在一个classic 的HTML表中.部分代码如下所示:
ngOnInit() {
this.store
.select(
createSelector(
(state: AppState) => state.userProperties,
(propObject: UserProperties) => propObject
)
)
.pipe(takeUntil(this.destroyed$))
.subscribe(({properties, total }) => {
this.propertyList = properties;
this.totalFound = total;
})
和呈现代码:
<tbody>
<ng-container *ngFor="let row of propertyList">
<tr>
<td>
</td>
<td class="limited">{{ row.id }}</td>
<td class="limited">{{ categoryLabels[row.category] | _: trans.lang }}</td>
<td class="limited">{{ contractLabels[row.contract_type] | _: trans.lang }}</td>
<td class="limited">{{ row.price }}</td>
<td class="limited">{{ row.city }}</td>
<td class="limited">
</td>
<td>
<div class="table-actions">
<button (click)="editProperty(row.id)" class="button button-icon">
<edit-icon></edit-icon>
</button>
<button *ngIf="row.deleted === 0" (click)="archiveProperty(row.id)" title="Delete this property"
class="button button-icon">
<img src="/assets/images/icons/delete-red.svg" />
</button>
<button (click)="toggleExpand(row.id)" class="button button-icon btn-expand">
<expand-icon [expanded]="expandedElements[row.id]"></expand-icon>
</button>
</div>
</td>
</tr>
</ng-container>
我注意到的问题是,如果我更改一行,例如我单击setStatus,这会更改数组的一行,所有表都会再次呈现(导致一些闪烁).
有没有一种方法可以告诉ANGLE只渲染数组中已更改的行?
解决方案(感谢@Dmytro Demyanenko): 将trackby添加到ngFor:
<ng-container *ngFor="let row of propertyList; trackBy: trackByFn">
并定义trackby函数:
trackByFn(index, row) {
return JSON.stringify(row);
}
只有当trackBy函数返回与上次返回的值不同的值时,Angular 才会重新呈现ngFor循环元素.在我的例子中,行中的某些数据可能会更改,然后需要重新呈现.