0

The following code hides my hamburger menu when not in use and I'm trying to use the following lines of code across multiple components:

ionViewWillEnter(){
    this.hamburgerMenu.enable(false)
}

ionViewWillLeave(){
    this.hamburgerMenu.enable(true)
}

I believe that it would be beneficial for my app if I can just create reusable method that I can call using a service.

Is there a way for me to access and modify ionic life cycle using a service? If not, what would be my other option to create a reusable method to show/hide my hamburger menu?

I already tried importing the Component interface in my service and I was expecting that by doing so, I can be able to access the component's lifecycle. However, I was stuck and don't know what to do after importing the said interface.

2 Answers2

0

It's not recommended to add Ionic lifecycle methods to a service, same goes for angular lifecycle methods. These methods are specifically designed to be used within their own components, not to be reused. Services are singletons and do not have lifecycle in the way components do. What you should do is:

Add ionViewWillEnter and ionViewWillLeave methods in each of your components and create a service that changes the hamburgerMenu variable.

-1

Create a Class define your methods.

export class MyHamburgerClass {
 @ViewChild('hamburger') hamburgerMenu;

 ionViewWillEnter(){
  this.hamburgerMenu.enable(false)
 }

 ionViewWillLeave(){
  this.hamburgerMenu.enable(true)
 }
}

export class MyComponent extends MyHamburgerClass implements OnInit {
  ...
}

Or create a directive - it's a best solution.

  @Directive({
   selector: '[myHamburgerDirective]',
  })
  export class MyHamburgerDirective {
   constructor(private elementRef: ElementRef<MyHamburgerComponent>) {
   }
   ionViewWillEnter(){
    this.hamburgerMenu.enable(false)
   }

   ionViewWillLeave(){
    this.hamburgerMenu.enable(true)
   }
  }

usage: <hamburger-menu myHamburgerDirective></hamburger-menu>

Eugene_Kr
  • 109
  • 3