Ionic 2 - Sidebar - Active Item

Hello,

Is there a new way / directive that we can use to make the sidemenu items active when their appropriate class / page is active ?

Is there another way to do it besides ng-class ?

Thanks.

@tonyawad88 thats a great idea! Currently something like this does not exis, but if you would like to open an issue or attempt a PR, that would be great!

2 Likes

I will try :)… I am currently researching how to get the current active page in the stack. Also I’m trying to avoid using Router. :slightly_smiling:

1 Like

I went back and used ngClass.

<button ion-item class="sidebar_buttons" *ngFor="#p of NavPages" 
        (click)="openPage(p)" 
        [ngClass]="{'sidebar_button_active':p.active}">
        <ion-icon name="{{p.icon}}" item-left></ion-icon>
        {{p.title}}
</button>
openPage(page) {
    //1. Loop through and set active attribute to False if it doesn't match.
    //   Set to True if it matches page titile
    for(var i = 0; i < this.NavPages.length; i++) {
      if(this.NavPages[i].title == page.title) this.NavPages[i].active = true;
      else this.NavPages[i].active = false;
    }
    //....
}

If you guys have an idea on how to improve this let me know please. Like should we have watchers on every sidemenu element, any other way we can reduce the watchers?

Thanks.

3 Likes

I think you can best use an Angular class attribute directive

  <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)" [class.active]="checkActivePage(p)">
    <ion-icon name="{{p.icon}}"></ion-icon>
    {{p.title}}
  </button>

And then in your TypeScript file add the following method.

  activePage: any;

  public openPage(page) {
    this.nav.setRoot(page.component);
    this.activePage = page;
  }

  public checkActivePage(page): boolean{
    return page === this.activePage;
  }

This should do the job :slight_smile:

2 Likes

Thanks for the update !

Will this work with deep linker though? I’m not sure how ionic redirects a page based on a URL.

Thanks for this. A bit more concise syntax, but does the same thing for my app:

        // Set active page title at root level
        this.pages.map(p => {
          p.isActive = (page.title == p.title);
        });

Hi i am using this in my project. I open jump a page to another page that is also listet in the side-menu. Now the activePage can not be set correctly (of course). Do you have an idea how i can get it working too? Should i use Events?

I have solved my problem. See here: https://stackoverflow.com/questions/45216213/navigate-to-page-and-highlight-menu-item-when-navigating-from-home-page

Sometimes it’s easy as that…

In Ionic 4, try this https://stackoverflow.com/a/37976498/9509575