Angular 动态组件加载器-无法读取属性';viewContainerRef';未定义的
我遵循Angular.io上广告横幅教程的所有步骤。但在所有设置结束后,我从该组件和函数中发现一个错误: Ad-banner.TS组件Angular 动态组件加载器-无法读取属性';viewContainerRef';未定义的,angular,angular-dynamic-components,elementref,Angular,Angular Dynamic Components,Elementref,我遵循Angular.io上广告横幅教程的所有步骤。但在所有设置结束后,我从该组件和函数中发现一个错误: Ad-banner.TS组件 loadComponent() { this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length; const adItem = this.ads[this.currentAdIndex]; const componentFactory = this.componen
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;
}
您的组件HTML应该是:-
<div class="ad-banner-example">
<h3>Advertisements</h3>
<ng-template ad-host></ng-template>
</div>
您的AdhostDirective应该位于模块的声明中
您应该调用这个.loadComponent();在ngoninit中。何时调用此函数?它应该在AfterViewInit或更高版本中调用。它与文档中的一样,但我将尝试您的建议。调用loadComponent()时,adHost未定义。loadComponent()从何处调用?构造函数(public viewContainerRef:viewContainerRef){}代码中有这个吗?@Aakash Garg我编辑了这篇文章,是的,我有它在目录中每个东西都在适当的位置,声明,EntryComponents和模块中声明内部的指令?
<div class="ad-banner-example">
<h3>Advertisements</h3>
<ng-template ad-host></ng-template>
</div>
@ViewChild(AdDirective, {static: true}) adHost: AdDirective;