0

I studied the code available on angular.io, and I replicated it in my scenario with a mat-tab-group. However, I would like to be able to use the ad-host directive inside a *ngFor. I tried it, and the directive is always undefined.

I searched here and, while there are several questions addressing this problem, I found no clear example on how to do this. The idea is that I have a mat-tab-group composed of several mat-tabs, which are loaded through a *ngFor directive. In each tab I would like to show a different component according to the selected index. Is there any way to achieve this?

Here is my modified stackblitz: as you can see it literally says this.adHost is undefined in the console.

Michael
  • 876
  • 9
  • 29

1 Answers1

2

You need to change the way you get a reference to your adHost.

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

It needs to be static: false (see documentation) because it's rendered dynamically by mat-tab, so it's not always in the template.

And don't call loadComponents in ngOnInit, since the view has not been rendered yet, so adHost will be undefined. Use ngAfterViewInit for instance. I just commented it.

Corrected stackblitz

Edit

Following your clarifications, I changed quite a lot of things (removed your setInterval, used @ViewChildren instead of ViewChild, use ngOnChanges to know when to render the data, etc.).

Here is the stackblitz example

Michael
  • 876
  • 9
  • 29
David
  • 33,444
  • 11
  • 80
  • 118
  • Unfortunately, this does not work the way I would like it to work. Maybe I have explained it poorly, bu the idea was to get a Component in each of the tabs, so if the first tab contains a HeroProfileComponent I should show a HeroProfileComponent in the first tab content, if the second is a HeroJobAdComponent it should show a HeroJobAdComponent inside, and so on and so forth. In your example, only the first tab shows the content, whereas the other ones remain empty. Note that if I move the `ng-template` outside the `mat-tab-group`, everything works, but I do not think that is a good approach. – Michael Apr 29 '20 at 09:18