【发布时间】: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