0

I am trying a load microapps on the right side of my screen on click of the tabs in the menu bar in angular 16.

I came across a dynamic component loading concept, was trying to experiment with it and am getting an issue with the same. Below is the code. Could you please let me know where I am going wrong in this particular scenario.


menu.component.ts

import { AfterViewInit, Component, OnInit, ViewChildren } from '@angular/core';
import { LandingDirective } from 'src/app/directive/landing.directive';
import { DataRetrievalService } from 'src/app/service/data-retrieval.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit, AfterViewInit {
  
  @ViewChild(LandingDirective, {static: true}) appLanding!: LandingDirective;

  menuoptions: any = []

  active = '';
  constructor(private dataRetrievalService: DataRetrievalService) { }

  ngAfterViewInit(): void {
    this.loadMicroapp();
  }

  ngOnInit(): void {
    this.menuoptions = this.dataRetrievalService.getMenuOptions();
    console.log("menuOptions: ", this.menuoptions);
    this.active = this.menuoptions[0].option;
    console.log("activeTab: ", this.active);
  }

  loadMicroapp() {
    console.log("microappComponent: ",this.appLanding);
    const { viewContainerRef }: LandingDirective = this.appLanding;
    console.log(viewContainerRef);
  }
}


menu.component.html

<div class="d-flex">
    <div ngbNav #nav="ngbNav" [(activeId)]="active" class="nav-pills flex-column" orientation="vertical">
        <ng-container *ngFor="let section of menuoptions" [ngbNavItem]="section.option">
            <button ngbNavLink (click)="loadMicroapp()">
                {{ section.option }}
            </button>
            <ng-template ngbNavContent>
                <p>Tab {{ section.option }} content</p>
                <ng-template appLanding></ng-template>
            </ng-template>
        </ng-container>
    </div>
    <div [ngbNavOutlet]="nav" class="mt-2"></div>
</div>

landing.directive.ts

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appLanding]'
})
export class LandingDirective {

  constructor(public viewContainerRef: ViewContainerRef) {}

}

Reference links used:

https://angular.io/guide/dynamic-component-loader

https://developer.okta.com/blog/2021/12/08/angular-dynamic-components

Akram
  • 23
  • 2

0 Answers0