【问题标题】:How to pass component to library (pass ng-template into component)如何将组件传递给库(将 ng-template 传递给组件)
【发布时间】:2020-05-07 19:35:04
【问题描述】:

我需要将迭代的组件传递给另一个组件,就像这样:

<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&lt;TemplateRef&lt;any&gt;&gt;;

我有 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 ?

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

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

组件-一个 HTML:

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

Component-b 静态文本。

【问题讨论】:

    标签: angular angular-components angular-library


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 2020-04-22
      • 2018-08-03
      • 2018-08-05
      • 2021-09-25
      • 1970-01-01
      • 2019-04-01
      • 2021-04-21
      • 1970-01-01
      相关资源
      最近更新 更多