允许使用ngFor
循环渲染后删除列表项,并在列表项中上下移动。
在列表上正确完成了移动和删除。但是将项目上移后,ngFor
会产生奇怪的结果:被移动的项目仍保留在原处,并且还被复制到所需的位置,而该位置处的项目未渲染(但列表本身仍然可以)
此外,在执行删除操作后,角度引发:
TypeError:无法读取null的“销毁”属性 在ViewContainerRef_.move ....
将项目下移可以按预期进行(所有列表操作均使用array.splice
方法进行。
围绕包装列表项组件的循环:
<ng-container *ngFor="let item of list; let itemIndex = index; trackBy: trackByItemId">
<ng-container *ngTemplateOutlet="itemTemplate; context: { $implicit: { item: item, index: itemIndex, service: listOperationsService} }"></ng-container>
</ng-container>
<ng-template #itemTemplate
let-data>
<app-list-item [item]="data.item"
[service]="data.service"
[index]="data.index">
</app-list-item>
</ng-template>
列出项目组件的模板:
<div class="item">
<app-item-content [model]="item"></app-item-content>
<button (click)="service.moveUp(index)">Move up</button>
<button (click)="service.moveDown(index)">Move down</button>
<button (click)="service.delete(index)">Delete</button>
<div>
trackBy
函数以返回简单项目的index
时,ngFor
会正确显示列表。但是,当trackBy
返回item.id
或我根本不提供任何trackBy
函数时,就会出现上述问题。ng-template
中的所有内容与其他ng-template
中的其他实例是隔离的,只要列表中没有相应的项目,它们就会被销毁。所以我用app-list-item
包装了ng-template
。 为什么ngFor
在上移项目时会重复该项目,而在已将其从列表中删除并引发错误时为什么不删除该项目?
我猜测组件嵌套和上下文中的某个地方存在问题。欣赏你的想法。
更新:当列表没有嵌套组件时,一切正常。 e。仅适用于ng-container
,ng-template
和纯HTML。由于重构原因,我决定使用嵌套组件。