ngFor循环如何与嵌套组件及其上下文一起使用?

时间:2018-10-11 21:53:39

标签: javascript angular ngfor ng-template

目标

允许使用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>

我尝试过的

  1. 当我提供trackBy函数以返回简单项目的index时,ngFor会正确显示列表。但是,当trackBy返回item.id或我根本不提供任何trackBy函数时,就会出现上述问题。
  2. 据我对Angular的了解,我假设ng-template中的所有内容与其他ng-template中的其他实例是隔离的,只要列表中没有相应的项目,它们就会被销毁。所以我用app-list-item包装了ng-template

问题

为什么ngFor在上移项目时会重复该项目,而在已将其从列表中删除并引发错误时为什么不删除该项目?

我猜测组件嵌套和上下文中的某个地方存在问题。欣赏你的想法。


更新:当列表没有嵌套组件时,一切正常。 e。仅适用于ng-containerng-template和纯HTML。由于重构原因,我决定使用嵌套组件。

0 个答案:

没有答案