angularangular-dynamic-componentselementref

Dynamic component loader - Cannot read property 'viewContainerRef' of undefined


im following all steps of the ad-banner tutorial on Angular.io. But at the end after all setup, i get an error comming from this component and function:

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) { }

}

Solution

  • Your component HTML should be :-

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

    You component Ts should have :-

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

    You AdhostDirective should be in declarations of your module.

    and you should be calling this.loadComponent(); in ngoninit.