Dvex Dvex - 9 months ago 81
TypeScript Question

How to show/hide menu items in side menu in app.html? Ionic 2

In my

app.component.ts
I define the pages that will go in my side menu.
And in my
app.html
I have my
<ion-menu>
with all menu items. However, there are some that are activated when the user logs on.

In my
app.component.ts
I get the user's token to know if I logged in (this is saved in the
localstorage
when the user logs in) and I save it in a variable and this I put it as conditional in my html using ngIf.

But as the user navigates through the application and clicks to logout, the side menu is not refreshed by more than removing the user's token from the localstorage.

This is my app.component.ts:

import { HomePage } from '../pages/home/home';
import { LoginPage } from './../pages/login/login';
import { OtherPage1 } from './../pages/others/other_one';
import { OtherPage2 } from './../pages/others/other_two';

export class MyApp {
@ViewChild('content') menu : NavController;
rootPage:any = HomePage;
public userToken;
login = LoginPage;
home = HomePage;
other_1 = OtherPage1;
other_2 = OtherPage2;

constructor(...) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
});

this.userToken = localStorage.getItem('idTokenUser');

[...]
}

goPage(page:any){
this.menu.setRoot(pagina);
this.menuCtrl.close();
}

logout(){
localStorage.removeItem('idTokenUser')
this.menu.setRoot(HomePage);
this.menuCtrl.close();
}

}


This is my app.html:

<ion-menu [content]="content" persistent="true">
<ion-header color="primary"></ion-header>
<ion-content>
<ion-list>
<button ion-item (click)="goPage(home)">
<ion-icon item-start name="home"></ion-icon>
Home</button>

<button ion-item *ngIf="userToken" (click)="goPage(other_1)">
<ion-icon item-start name="clipboard"></ion-icon>
Other 1</button>

<button ion-item *ngIf="userToken" (click)="goPage(other_2)">
<ion-icon item-start name="people"></ion-icon>
Other 2</button>

<button ion-item *ngIf="!userToken" (click)="goPage(login)">
<ion-icon item-start name="key"></ion-icon>
Login</button>

<button ion-item *ngIf="userToken" (click)="logout()">
<ion-icon item-start name="close-circle"></ion-icon>
Logout</button>

</ion-list>
</ion-content>
</ion-menu>

<ion-nav [root]="hom" #content></ion-nav>


What is the way to remove item in side menu, when the user clicks to log out, at any time?

iTR iTR
Answer Source

Change the logout function to

logout(){
    localStorage.removeItem('idTokenUser');
    this.userToken = null;
    this.menu.setRoot(HomePage);
    this.menuCtrl.close();
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download