Ionic 2 - Sidebar - Active Item


#1

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.


#2

@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!


#3

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:


#4

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.


#5

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:


#6

Thanks for the update !


#7

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


#8

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);
        });