Search code examples
angularangular-materialangular-directivemat-tab

Dynamically load components inside *ngFor in Angular 9


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.


Solution

  • 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