How to create dynamic side navigation menu&Submenu in ionic2/3

一笑奈何 提交于 2019-12-06 11:41:45

Here is a working example

First, you need a provider to save your menu items. In the example above:
app-service.ts

import { Subject } from 'rxjs/Subject';

userId = 1; //this varible store your userId
menuItems = []; //this array store your menu items
menuSubject: Subject<string> = new Subject<string>(); //Here is the subject will broadcast an event whenever menu item change

//this function is called when you change the user
changeUser(userId) {
    this.userId = userId;
    //Get menu data from server then update your menu
     if(userId == 1){
        this.menuItems = [...] //See all code in the example above
     }
    this.menuSubject.next("new menu items have arrived");
  }

Second, in your show the menu in your app:
app.html:

<ion-menu [content]="content" swipeEnabled="true" class="menu" type="reveal" width="100px">
  <ion-list>
    <ion-item class="menu-item" *ngFor="let item of menuItems" (click)="itemClick(item.component)">{{item.name}}</ion-item>
  </ion-list>
</ion-menu>
<ion-nav id="nav" #content [root]="rootPage"></ion-nav>

app.component.ts:

import { Platform, MenuController, App } from 'ionic-angular';
constructor(platform: Platform,
    private appService: AppService,
    private menuCtrl: MenuController){
    this.menuItems = this.appService.menuItems;
    //Subscribe whenever menu items changed
    this.appService.menuSubject.asObservable().subscribe(() => {
      this.menuItems = this.appService.menuItems;
      this.menuCtrl.open();
    })
}

//This function is called whenever menu item clicked
itemClick(component){
    this.rootPage = component;
}

Finnally, whenever you change the user (by login or whatever you want), call the changeUser method in appService home.ts:

//See the full code in example
this.appService.changeUser(+userId);

I am not an ionic guy so dont know the ionic way, but i have done this in angular way. It might help you to get the gist of it. Instead of the response having the component names, you can have an additional field called path which will have the route defined like this.

path: '/home'

So when the user clicks on the item , you can write login to route to the mentioned path.

For your second question you can refer here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!