sebaferreras / Ionic3-MultiLevelSideMenu

Ionic 3 demo of a two-level side menu.
MIT License
136 stars 55 forks source link

Remove item from side menu #29

Closed Martin317 closed 6 years ago

Martin317 commented 6 years ago

How can i remove and add items to menu dinamically? For example, when i Logout, i need to remove "Logout" item. I try to splice the options array but nothing happends. Thanks! My code:

 selectOption(option: MenuOptionModel): void {
    if (option.custom && option.custom.isLogout) {
      this.logout();
      this.options.splice(4,1);
    } else if (option.component) {
      this.goToPage(option.component);
    }
    this.closeMenu();
  }
sebaferreras commented 6 years ago

Hi! In order to improve the performance of the app, the side menu component uses OnPush as the change detection strategy.

The thing is that Angular does not recognize that the input has changed when you add/remove one item from that array. Instead, you'd need to change the entire array so Angular knows that this is a different array and the component should be updated.

I think something like this should be enough:

// ...
this.options.splice(4,1);
this.options = [...this.options];
// ...

You could also create a private method where you initialize all the options of the side menu using a boolean parameter to decide if the logout should be added to the list

private initializeOptions(isLoggedIn: boolean): Array<MenuOptionModel> {
    let options: Array<MenuOptionModel> = [];

    // Add the options based on if the user is logged in or not...
    // ...

    return options;
}

And then instead of using splice to modify the array with the options, you could use that method:

// ...
this.options = this.initializeOptions(false);
// ...
Martin317 commented 6 years ago

Thanks! its working. (No sabia que eras de españa sino hablaba en español).

sebaferreras commented 6 years ago

Si, soy argentino en realidad pero me pareció mejor responder en inglés porque tu pregunta es muy buena y es mejor si queda explicado en inglés por si le sirve a alguien más... Un abrazo @Martin317 !