How to Create Multilevel Accordion Menu in Ionic 5 Angular

Throughout this Ionic 5 Multi-level menu tutorial, you will learn how to build collapsible accordion navigation in an Ionic 5 Angular application from scratch.

This ionic sidebar accordion navbar example will explain how to create a multi-level sidebar navigation user interface component in the ionic application without using the third-party library.

Why do we need an Ionic 5 accordion example? Sometimes we have many categories of products or services that we want to show to our customers or site visitors. We can not fit every menu item in the sidebar.

To tackle such kind of problem in ionic, we can use the multi-level accordion menu, which will easily display enumerable nav items in the collapsible form.

Ionic 5 Angular Multilevel Accordion Menu with Sub-menu Example

  • Step 1: Install Ionic CLI
  • Step 2: Download Ionic Project
  • Step 3: Create Ionic Pages
  • Step 4: Create Multi Nav JSON
  • Step 5: Set Up Angular Service
  • Step 6: Implement Multi Level Accordion Menu
  • Step 7: Start Ionic App

Install Ionic CLI

In the beginning, you require to install the ionic cli, and ionic cli is a go-to tool for ionic development.

You can install the ionic cli using the provided command.

npm install -g @ionic/cli

Download Ionic Project

In this section, you require to use the command to install a brand new ionic, angular app, use the side-menu tag to generate a ready-made ionic application.

ionic start ionic-blog sidemenu --type=angular

Create Ionic Pages

In this step, you need to use the ionic cli command and generate a bunch of pages that we will use to create multilevel navigation in ionic.

ionic g page nav01
ionic g page nav02
ionic g page nav03
ionic g page nav04
ionic g page nav05
ionic g page nav06
ionic g page nav07
ionic g page nav08
ionic g page nav09
ionic g page nav10
ionic g page nav11
ionic g page nav12
ionic g page nav13
ionic g page nav14
ionic g page nav15

Create Multi Nav JSON

In this step, you require to create the assets/multi-nav.json file, then create the accordion multi navigation structure as defined below.

[{
  "name": "Menu 1",
  "nav": [{
      "name": "menu-1-1",
      "nav": [{
          "name": "menu-1-1-1",
          "nav": [{
              "name": "menu-1-1-1-1",
              "url": "/menu01"
            },
            {
              "name": "menu-1-1-1-2",
              "url": "/menu02"
            }
          ]
        },
        {
          "name": "menu-1-1-2",
          "nav": [{
              "name": "menu-1-1-2-1",
              "url": "/menu03"
            },
            {
              "name": "menu-1-1-2-2",
              "url": "/menu04"
            }
          ]
        }
      ]
    },
    {
      "name": "menu-1-2",
      "nav": [{
          "name": "menu-1-2-1",
          "nav": [{
              "name": "menu-1-2-1-1",
              "url": "/menu05"
            },
            {
              "name": "menu-1-2-1-2",
              "url": "/menu06"
            }
          ]
        },
        {
          "name": "menu-1-2-2",
          "nav": [{
              "name": "menu-1-2-2-1",
              "url": "/menu07"
            },
            {
              "name": "menu-1-2-2-2",
              "url": "/menu08"
            }
          ]
        }
      ]
    }
  ]
},
{
  "name": "Menu 2",
  "nav": [{
      "name": "menu-2-1",
      "nav": [{
          "name": "menu-2-1-1",
          "nav": [{
              "name": "menu-2-1-1-1",
              "url": "/menu09"
            },
            {
              "name": "menu-2-1-1-2",
              "url": "/menu10"
            }
          ]
        },
        {
          "name": "menu-2-1-2",
          "nav": [{
              "name": "menu-2-1-2-1",
              "url": "/menu11"
            },
            {
              "name": "menu-2-1-2-2",
              "url": "/menu12"
            }
          ]
        }
      ]
    },
    {
      "name": "menu-2-2",
      "nav": [{
          "name": "menu-2-2-1",
          "nav": [{
              "name": "menu-2-2-1-1",
              "url": "/menu13"
            },
            {
              "name": "menu-2-2-1-2",
              "url": "/menu14"
            }
          ]
        }
      ]
    }
  ]
}]

Set Up Angular Service

Now, you have to create the ionic, angular service using the given command.

Angular service helps write the reusable logic for managing the common task for your angular components.

ionic g service accordion-nav

Head over to app/accordion-nav.service.ts and update the provided code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class AccordionNavService {

  url = 'assets/multi-nav.json';

  constructor(private http: HttpClient) { }

  multiNav() {
    return this.http.get(this.url);
  }
  
}

Next, we will open the src/app/app.module.ts file and add HttpClientModule dependency in our App Module.

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 { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})

export class AppModule {}

Implement Multi Level Accordion Menu

Next, we will give the final touch to our ionic multi-nav functionality, so to make the collapsible menu work in ionic, first import the AccordionNavService.

This will help in the process of implementing the Collapsible Multi Nav in ionic.

Update src/app/app.component.ts file.

import { Component } from '@angular/core';
import { AccordionNavService } from './accordion-nav.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})

export class AppComponent {

  navCat1 = null;
  navCat2 = null;
  navCat3 = null;

  public PAGES: any  = [ ];

  constructor( private accNav: AccordionNavService ) {
    this.accNav.multiNav().subscribe((item) => {
      this.PAGES = item;
    });
  }

  menuCat1(res: string) {
    if (this.isMenu1Displayed(res)) {
      this.navCat1 = null;
    } else {
      this.navCat1 = res;
    }
  }

  isMenu1Displayed(res: string) {
    return this.navCat1 === res;
  }

  menuCat2(res: string) {
    if (this.isMenu2Displayed(res)) {
      this.navCat2 = null;
    } else {
      this.navCat1 = res;
      this.navCat2 = res;
    }
  }

  isMenu2Displayed(res: string) {
    return this.navCat2 === res;
  }

  menuCat3(res: string) {
    if (this.isMenu3Displayed(res)) {
      this.navCat3 = null;
    } else {
      this.navCat2 = res;
      this.navCat3 = res;
    }
  }

  isMenu3Displayed(res: string) {
    return this.navCat3 === res;
  }

  clearMenu() {
    this.navCat1 = null;
    this.navCat2 = null;
    this.navCat3 = null;
  }

}

Here in this step, you require to add the HTML code; it will decide the multi-level navigation structure. So, update the given code in the app.component.html file.

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-content>
        <ion-list lines="full">
          <ion-menu-toggle auto-hide="false" class="first-menu"></ion-menu-toggle>
          <ion-item *ngFor="let p of PAGES; let i=index;" [routerDirection]="'root'" (click)="menuCat1('res'+i)"
            [ngClass]="{active: isMenu1Displayed('res'+i)}">
            <ion-label>
              <ion-icon [name]="isMenu1Displayed('res'+i) ? 'chevron-down-outline' : 'chevron-forward-outline'"
                slot="end"></ion-icon>
              {{p.name}}
              <ul *ngIf="isMenu1Displayed('res'+i)" class="menu1">
                <li *ngFor="let i1 of p.nav; let j=index;" (click)="menuCat2('res'+i+'res'+j)"
                  [ngClass]="{active: isMenu2Displayed('res'+i+'res'+j)}">
                  <ion-icon
                    [name]="isMenu2Displayed('res'+i+'res'+j) ? 'chevron-down-outline' : 'chevron-forward-outline'"
                    slot="end"></ion-icon>
                  {{i1.name}}
                  <ul *ngIf="isMenu2Displayed('res'+i+'res'+j)" class="menu2">
                    <li *ngFor="let i2 of i1.nav; let k=index;" (click)="menuCat3('res'+i+'res'+j+'res'+k)"
                      [ngClass]="{active: isMenu3Displayed('res'+i+'res'+j+'res'+k)}">
                      <ion-icon
                        [name]="isMenu3Displayed('res'+i+'res'+j+'res'+k) ? 'chevron-down-outline' : 'chevron-forward-outline'"
                        slot="end"></ion-icon>
                      {{i2.name}}
                      <ul *ngIf="isMenu3Displayed('res'+i+'res'+j+'res'+k)" class="menu3">
                        <li *ngFor="let i3 of i2.nav; let l=index;" [routerLink]="[i3.url]">
                          <ion-menu-toggle auto-hide="false" class="first-menu">{{i3.name}}</ion-menu-toggle>
                        </li>
                      </ul>
                    </li>
                  </ul>
                </li>
              </ul>
            </ion-label>
          </ion-item>
        </ion-list>
      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Go to app.component.scss, in this file you need to add the css for styling the nav item ui module.

.menu1, 
.menu2, 
.menu3 {
  padding: 12px;
  list-style: none;
  li {
      padding: 12px 0 12px 12px;
      border-top: 1px solid white;
  }
}

Start Ionic App

Now, you require to execute the given below command; below command is accountable for installing the ionic lab package which is helpful in interpreting our TypeScript code into JavaScript and load the app onto the browser.

npm i @ionic/lab --save-dev
ionic serve -l

Create Multilevel Accordion Menu in Ionic 5 Angular App

Summary

In this step-by-step guide, we have seen how to create an accordion menu with a submenu in the ionic app. To display the angular multi-level accordion menu, we used the json file to create the nav structure for the menu and submenus and used the HTTP client to add the multi nav menu in the ionic, angular app.