[英]Dynamic component loader - Cannot read property 'viewContainerRef' of undefined
im following all steps of the ad-banner tutorial on Angular.io.我遵循 Angular.io 上的广告横幅教程的所有步骤。 But at the end after all setup, i get an error comming from this component and function:但在所有设置结束后,我收到来自此组件和 function 的错误:
Ad-banner.component TS 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;
}
I get the log correctly, the hero data comes to the home component where I'll display the ads, but not with the error, so can anyone sort me out?我正确获取了日志,英雄数据进入了我将显示广告的主页组件,但没有出现错误,所以任何人都可以解决我的问题吗?
EDIT The Main Directive编辑主要指令
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ad-host]'
})
export class AdDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Your component HTML should be:-您的组件 HTML 应该是:-
<div class="ad-banner-example">
<h3>Advertisements</h3>
<ng-template ad-host></ng-template>
</div>
You component Ts should have:-你的组件 Ts 应该有:-
@ViewChild(AdDirective, {static: true}) adHost: AdDirective;
You AdhostDirective should be in declarations of your module.您 AdhostDirective 应该在您的模块的声明中。
and you should be calling this.loadComponent();你应该调用 this.loadComponent(); in ngoninit.在 ngoninit.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.