Search code examples
angularionic-frameworkangular-ui-routerionic4

Ionic 4 Side Menu set active link on initial first navigation


I have a side menu in my app which works fine for showing the active link. My only problem is when I run the app initially, the active link is not highlighted. I subscribed to the RouterConfigLoadEnd event to set the selected link, but I don't think that's the right way because if I navigate to another link it will keep setting it. Any suggestions?

constructor(private router: Router) {
  const initialPage = this.router.events.subscribe((event: RouteConfigLoadEnd) => {
    console.log('inital load');
    this.selectedPath = '/menu/forecast';
  });
  // Tried to unsub here but then the active link will not be active at start
  // initalPage.unsubscribe();
  this.router.events.subscribe((event: RouterEvent) => {
    if (event && event.url) {
      console.log('set active');
      this.selectedPath = event.url;
    }
  });
}

Solution

  • You can subscribe to NavigationEnd Event of Router that triggers each time navigation to a page ends successfully. Official DOc

    this.router.events.subscribe((events:NavigationEnd)=>
              {
                this.selectedPath = events.url;
              })