如何将组件传递给库(将 ng-template 传递给组件)

How to pass component to library (pass ng-template into component)

我需要将迭代组件传递给另一个组件,类似这样:

<component-a>
  <ng-template *ngFor="let item of items">
    <component-b [options]="item"></component-b>
  </ng-template>
</component-a>

我尝试了不同的方式来显示组件-b,但不幸的是没有得到结果。 其中之一使用 @ContentChildren 装饰器 @ContentChildren(TemplateRef, {descendants: true}) template: QueryList<TemplateRef<any>>;

我有 templateRefs 数组并使用 forEach createEmbeddedView 进入 ngAfterContentInit

this.template.forEach(item => {
  this.viewContainerRef.createEmbeddedView(item);
});

如果我在 ngAfterContentInit 中这样做,我会遇到下一个错误

AppComponent.ngfactory.js? [sm]:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'options: undefined'. Current value: 'options: [object Object]'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?

但组件显示。 我缺少什么? Maby 我应该走另一条路吗?

如果我把它移到 ngAfterContentChecked 我得到了无限循环

组件-a HTML:

<div class="component-a">
  <ng-container></ng-container>
  <ng-content></ng-content>
</div>

Component-b 静态文本。

由 this.viewTemplateRef.createEmbeddedView(item).detectChanges();

解决