【问题标题】:Dynamic component loader - Cannot read property 'viewContainerRef' of undefined动态组件加载器 - 无法读取未定义的属性“viewContainerRef”
【发布时间】:2020-05-29 14:24:27
【问题描述】:

我按照 Angular.io 上的广告横幅教程的所有步骤进行操作。但在所有设置结束后,我收到来自此组件和功能的错误:

Ad-banner.component TS

loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    const adItem = this.ads[this.currentAdIndex];

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);

    const viewContainerRef = this.adHost.viewContainerRef; ---->ERROR comes from this Line
    viewContainerRef.clear();

    const componentRef = viewContainerRef.createComponent(componentFactory);
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

我正确获取了日志,英雄数据出现在我将显示广告的主页组件中,但没有出现错误,所以任何人都可以解决我的问题吗?

编辑 主要指令

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]'
})
export class AdDirective {

  constructor(public viewContainerRef: ViewContainerRef) { }

}

【问题讨论】:

  • 什么时候调用这个函数?它应该在 AfterViewInit 或更高版本中调用。
  • 它的 onInit 就像在文档中一样,但我会尝试你的建议
  • this.adHost 在调用 loadComponent() 时未定义。 loadComponent() 是从哪里调用的?
  • constructor(public viewContainerRef: ViewContainerRef) { } 代码中有这个吗?
  • @Aakash Garg 我已经编辑了帖子,是的,我在指令中有它

标签: angular angular-dynamic-components elementref


【解决方案1】:

您的组件 HTML 应该是:-

<div class="ad-banner-example">
              <h3>Advertisements</h3>
              <ng-template ad-host></ng-template>
            </div>

你的组件 Ts 应该有:-

@ViewChild(AdDirective, {static: true}) adHost: AdDirective;

您的 AdhostDirective 应该在您的模块的声明中。

你应该调用 this.loadComponent();在 ngoninit 中。

【讨论】:

  • 一切就绪,声明,入口组件
  • 和模块声明中的指令?
猜你喜欢
  • 2018-09-21
  • 2018-06-28
  • 2021-11-24
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 2017-10-28
  • 2019-06-08
  • 2020-10-30
相关资源
最近更新 更多