Dynamic Menu loading data from BE using Angular 8 & Metismenu

424 Views Asked by At

I´m trying to migrate a project that is using Thymeleaf to Angular 8. The menu is implemented using MetisMenu loading it´s data from BE (rest api).

The problem

The issue is that the menu becomes unresponsive after a reload of the page or any navigation.

The code

main-menu.component.html

<div id="navigation">
    <ul class="nav" id="side-menu">
        <li *ngFor="let item of menu?.items">
            <a href='{{item.href}}'>
                <i class="{{item.icon}}"></i> 
                <span>{{item.text}}</span> 
                <span *ngIf="item?.subitems.length > 0" class="fa arrow"></span>
            </a>
            <ul *ngIf="item?.subitems.length > 0" id="{{item.code}}" class="nav nav-second-level collapse">
                <li class="nav nav-second-level" *ngFor="let subitem of item?.subitems">
                    <a href="{{subitem.href}}">{{subitem.text}}</a>
                </li>
            </ul>
        </li>
    </ul>
</div>

main-menu.component.ts

import { Component, OnInit } from '@angular/core';
import { MenuModel } from './menu-model';
import { MenuDataProviderService } from './menu-data-provider.service';

@Component({
  selector: 'app-main-menu',
  templateUrl: './main-menu.component.html',
  styleUrls: ['./main-menu.component.css']
})
export class MainMenuComponent implements OnInit {

  constructor(private menuService : MenuDataProviderService) {

  }

  menu: MenuModel;

  ngOnInit(): void {
    this.menuService.getMenu('MAIN', 'admin').subscribe(data => this.menu = data);
  }
}

MetisMenu is initialized this way

if (document.getElementById('side-menu') != null) {
    $('#side-menu').metisMenu();
}

inside a general script that has been added to angular configuration.

 "scripts": [
          "./node_modules/jquery/dist/jquery.js",
          "./node_modules/bootstrap/dist/js/bootstrap.js",
          "./node_modules/metismenu/dist/metismenu.js",
          "src/app-script.js" //general app script
        ]
      },

Debugging the app, saw that when metisMenu initialization is called, the menu doest not have its childrens (data has not been loaded).

I tried moving metisMenu initialization to the component ts file, using angular lifecycle hooks (AfterViewInit and AfterContentInit), but nothing worked.

I wonder if there existis any way to listen to the data subscription in order to trigger the menu initialization when ready.

0

There are 0 best solutions below