how to detect ion-menu close event on different page in ionic 5

Viewed 1379

I want to perform some functionality when ion-menu is closed, on different pages. ion-menu event work for that menu page only not on other page

2 Answers

Since ion-menu typically resides within app.component and you want state from it to be available to other components you need to leverage a "shared service".

Create a shared service (ng g s shared):

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
 providedIn: 'root'
})
export class SharedService {

 private menuClosed = new BehaviorSubject(true); // set whatever default value;

 updateMenuState(state: boolean) {
   this.menuClosed.next(state)
 };

}

Now import into the app.component and add method that you will link ionWillClose and ionWillOpen to:

import { Component } from '@angular/core';
//..other imports
import { SharedService } from './services/shared.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
})
export class AppComponent {

  //...

  constructor(
    public sharedService: SharedService
  ) {

  };

  updateMenuState(state: boolean) {
    this.sharedService.updateMenuState(state)
  }

  //...

}

And in your app.component.html:

<ion-menu (ionWillClose)="updateMenuState(false)" (ionWillOpen)="updateMenuState(true)"></ion-menu>

After that import shared service in whatever other components you have and subscribe to the BehaviorSubject for changes.

Write a function with your desired code and put it in app.component.ts or a service that is shared everywhere. then in your ion-menu tag use the event ionWillClose to execute your function.

like this:

<ion-menu (ionWillClose)="muFunction()"></ion-menu>

ionWillClose event will be emitted when the menu is about to be closed.

Related