Component Factory Resolver does not load a component

  angular, html, javascript, typescript

I use ngx-bootstrap to load tabs.

When I want to render a component in a dependency that is selected it doesn’t work for me at all.
Check code:

<tabset class="w-100">
    <tab heading="Job Details"
         id="upcoming-bookings"
         (selectTab)="render('ViewJobComponent'); onSelectTab($event);"
         >
        <div class="content-light-box"> 
            <ng-template ad-host></ng-template> 
        </div>
    </tab>  
    <tab heading="Log"
         id="account-departments"
         (selectTab)="render('ViewLogComponent'); onSelectTab($event)">
         <div class="content-light-box"> 
            <ng-template ad-host></ng-template>
        </div> 
    </tab> v> 
    </tab> 
</tabset>

I need to use (selectTab) function because (click) no work for this.

  public components = [ViewJobComponent, ViewLogComponent];
  public currentComponent = null;
  @ViewChild(AdDirective) adHost!: AdDirective;
  public activeTab: any;


  public onSelectTab(tab: TabDirective) {
    this.activeTab = tab.id; 
}

public render(t: any): void {
  console.log('t' , t) 
  const index = Math.round(Math.random());
  const currentComponent = this.components[t];
  
  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(currentComponent as any);

  let viewContainerRef = this.adHost.viewContainerRef;
  viewContainerRef.clear();

  let componentRef = viewContainerRef.createComponent(componentFactory);
}

If need console.log for both function inside when console.log(tab) inside onSelectTab function i got result.

If I console.log(t) inside render() function i always got undefined.

This example work:

public render(t: any): void {
  console.log('t' , t) 
  const index = Math.round(Math.random());
  const currentComponent = this.components[1]; // load 1 index WORK

  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(currentComponent as any);

  let viewContainerRef = this.adHost.viewContainerRef;
  viewContainerRef.clear();

  let componentRef = viewContainerRef.createComponent(componentFactory);
}

I modeled on this:

https://stackblitz.com/edit/angular-componentfactoryresolver-example-e4urmu?file=src%2Fapp%2Fapp.component.ts

I also made the adHost directive don’t worry, that’s not the problem.

I also tried to pass him an index of 0 or 1 not working.

Source: Angular Questions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.