Add Dynamic Side Menu in Ionic 6 App with Active Class

Last updated on: by Digamber
A comprehensive Ionic step by step tutorial, Learn how to implement side menu dynamically in Ionic app with active class for selected page.

As we know, Ionic offers tons of UI components to create a Hybrid mobile application in lesser time. Most often, we fall into the situation where we need to use side menu navigation components to enhance the user experience.

The side menu looks intuitive and attractive and Implementing the side menu in Ionic is very easy. It is even considered best from the user experience’s perspective.

The side menu component in the view slides in from the left, and slide position is changeable. The menu items are a direct sibling to the root content items.

We will build the menu items from an array of pages and show the pages with content area, along with that, we will dynamically set the active class for the selected url.

Ionic 6 Custom Side Bar Menu Example

  • Step 1: Install Ionic App
  • Step 2: Generate Pages
  • Step 3: Setting Up Side Menu Routes
  • Step 4: Install StatusBar and SplashScreen Plugins
  • Step 5: Update StatusBar and SplashScreen Modules in AppModule
  • Step 6: Implement Dynamic Side Bar Menu in Ionic
  • Step 7: Add Hamburger Toggle Button
  • Step 8: Test Sidebar Menu Feature

Install Ionic App

First, Install the latest version of Ionic CLI on your device.

npm install -g ionic@latest

Now, you are all set to generate a new blank Ionic project, run the following command.

ionic start ionic-side-menu-tabs blank --type=angular

Once the new Ionic app is created then get head over to the project directory.

cd ionic-side-menu-tabs

Generate Pages

In this demo app, we need some pages so that we can show these pages in the sidebar menu items.

Run the below command to generate the pages.

ng generate page login
ng generate page register
ng generate page dashboard

Setting Up Side Menu Routes

Let us define the empty path, redirect to functionality within the routes. We have created the dashboard page to the default page hence ppen the app-routing.module.ts file and replace the existing code with the given below code.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full'
  },
  {
    path: 'login',
    loadChildren: () => import('./login/login.module').then( m => m.LoginPageModule)
  },
  {
    path: 'register',
    loadChildren: () => import('./register/register.module').then( m => m.RegisterPageModule)
  },
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then( m => m.DashboardPageModule)
  },
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Install StatusBar and SplashScreen Plugins

In this step, you need to install StatusBar and SplashScreen Plugins in Ionic Angular app.

ionic cordova plugin add cordova-plugin-statusbar
npm install @ionic-native/status-bar
ionic cordova plugin add cordova-plugin-splashscreen
npm install @ionic-native/splash-screen

Update StatusBar and SplashScreen Modules in AppModule

In this step, you required to import Platform, StatusBar and SplashScreen Plugins in AppModule class, also register these services in providers array.

Open and add code in app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
// Import modules
import { Platform } from '@ionic/angular';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    Platform,
    StatusBar,
    SplashScreen,
    { 
      provide: RouteReuseStrategy, 
      useClass: IonicRouteStrategy 
    }
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

Implement Dynamic Side Bar Menu in Ionic

Now, we will start implementing the dynamic sidebar menu into our ionic app, consequently open the app.component.ts file, add the following code in it.

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  activePageTitle = 'Dashboard';
  Pages = [
    {
      title: 'Dashboard',
      url: '',
      icon: 'albums'
    },
    {
      title: 'Login',
      url: '/login',
      icon: 'person'
    },
    {
      title: 'Register',
      url: '/register',
      icon: 'person'
    }
  ];
  constructor(
    private platform: Platform,
    private statusBar: StatusBar,
    private splashScreen: SplashScreen,
  ) {
    this.initializeApp();
  }
  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
}

To show the dynamic pages in the Ionic side menu, create the array of the pages with the page title, url and icons’ names.

We defined the activePageTitle variable to show the active class for the selected route.

Open app.component.html and add the following code:

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list id="inbox-list">
          <ion-list-header>Hello! John</ion-list-header>
          <ion-note>johndoe@gmail.com</ion-note>
          <ion-menu-toggle auto-hide="false" *ngFor="let pages of Pages; let i = index">
            <ion-item (click)="activeIndex = i" routerDirection="root" [routerLink]="[pages.url]" lines="none"
              detail="false" [class.selected]="activeIndex == i">
              <ion-icon slot="start" [ios]="pages.icon + '-outline'" [md]="pages.icon + '-sharp'"></ion-icon>
              <ion-label>{{ pages.title }}</ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>
      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Now, define the ion-menu directive with type overlay

Inside the ion-content, we added the ion-list and ion-menu-toggle and added the ngFor loop for showing the ionic pages dynamically in the side bar menu component.

The [routerLink] directive is the dynamic path for the associated menu item.

We also supply routerDirection and pass the root value to it. It is used to apply the useful screen transition animation to the navigation.

Also note that, you supply the main-content to the ion-menu directive and also pass the same id to the ion-router-outlet.

Add Hamburger Toggle Button

To show the side menu’s hamburger icon using a toggle click button, you have to add it on every page with ion-menu-button directive.

Open and add following code in app/login/login.page.html file:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button autoHide="false"></ion-menu-button>
    </ion-buttons>
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>

Open and add following code in app/register/register.page.html file:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button autoHide="false"></ion-menu-button>
    </ion-buttons>
    <ion-title>Register</ion-title>
  </ion-toolbar>
</ion-header>

Open and add following code in app/dashboard/dashboard.page.html file:

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-menu-button autoHide="false"></ion-menu-button>
    </ion-buttons>
    <ion-title>Dashboard</ion-title>
  </ion-toolbar>
</ion-header>

Test Sidebar Menu Feature

Start the application using the following command on the browser:

npm install @ionic/lab --save-dev
ionic serve --lab

Ionic Custom Side Bar Menu Example

Conclusion

Finally, Ionic dynamic side bar menu example is over. We have completed Ionic side menu tutorial, in this tutorial, we looked at how to implement dynamic side menu with Ionic pages, and we also learned to apply the active class for the selected route.

If you are getting started with a new Ionic application, you will notice that a dynamic side menu system is already prepared for you.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.