自定义结构指令创建了太多元素

Custom structural directive creates too many elements

我创建了我的自定义结构指令,它应该为传递的项目数组中的每个元素呈现宿主元素:

@Directive({
  selector: '[appItems]'
})
export class ItemsDirective implements OnInit, OnChanges {

  @Input('appItemsOf')
  items: any[];

  constructor(private container: ViewContainerRef,
              private template: TemplateRef<any>) {
  }

  ngOnInit(): void {
    this.container.createEmbeddedView(this.template);
  }

  ngOnChanges(): void {
    this.container.clear();

    for (const item of this.items) {
      if (item) {
        this.container.createEmbeddedView(this.template, {
          $implicit: item,
          index: this.items.indexOf(item)
        });
      }
    }
  }
}

用法:

<div *appItems="let item of items">
  Item: {{ item.name }}
</div>

不幸的是,它打印出:

Item: 1
Item: 2
Item: 3
Item:

正在创建和呈现最后一个元素,尽管项目数组看起来像:

items = [
    {
        name: '1'
    },
    {
        name: '2'
    },
    {
        name: '3'
    }
]

我创建了一个 https://stackblitz.com/edit/angular-qwatckstackblitz 来显示这个问题。

为什么会这样,应该如何正确处理?

为什么要在 ngOnInit 中创建这个,因为这是创建额外的一个。评论此行后,多余的项目将消失。

  ngOnInit(): void {
    // this.container.createEmbeddedView(this.template);
  }

目前,完成了以下工作:

  1. 指令实例已创建
  2. NgOnChanges 被调用
  3. NgOnInit 被调用

所以基本上,一旦您为您的集合创建了 N 个视图,您就可以在 NgOninit 期间创建另一个视图,从而在您的模板中生成 N+1 个嵌入式视图。

只需删除NgOnInit的内容。