0

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

}
9
  • When you call this function? It should be called in AfterViewInit or later. Commented May 29, 2020 at 14:27
  • its onInit like in the docs, but i'll try your sugestion Commented May 29, 2020 at 14:32
  • this.adHost is undefined when loadComponent() is called. Where is loadComponent() called from? Commented May 29, 2020 at 14:33
  • constructor(public viewContainerRef: ViewContainerRef) { } have this in code? Commented May 29, 2020 at 14:34
  • @Aakash Garg Ive edited the post, yes I have it's in the Directive Commented May 29, 2020 at 14:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

every thing is in place, declarations, entrycomponents
and the directive inside declarations in module?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.