Display Login/logout button in the sidebar
This tutorial will show you how to hide your login menu from the Sidebar and eventually after login option it will show logout option along with other menu items in the Sidebar. When user will active then it will show only logout option, until it will show login.
Let’s start how to do it.
As we can assume that you have some basic knowledge of HTML and angular 6 and also familiar with ionic 3 framework. So, first of all, write your simple login form code with username and password input field with a login button.
Login Page(login_page.html):
<ion-content> <form [formGroup]="loginForm" (ngSubmit)='login()'> <ion-item> <ion-label stacked> <h2 class="h2-Style">Username</h2></ion-label> <ion-input type="email" formControlName="userName"></ion-input> </ion-item> <ion-item> <ion-label stacked><h2 class="h2-Style">Password</h2></ion-label> <ion-input type="password" formControlName="password"></ion-input> </ion-item> <button ion-button full class="login-Style" >Log In</button> </form> </ion-content>
Using the on click() function and give function name login() function which was described in the .ts file. And after writing your TypeScript code simply put this line in your login() function.
this.events.publish('user:login');
Here I will put login.ts code, apply this code:
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, LoadingController, Events } from 'ionic-angular'; import { Validators, FormBuilder, FormGroup } from '@angular/forms'; import { Storage } from '@ionic/storage'; @IonicPage() @Component({ selector: 'page-login', templateUrl: 'login.html', }) export class LoginPage { public loginForm: FormGroup; public usercreds; constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder, public loadCtrl: LoadingController,private alertCtrl: AlertController, private storage: Storage, public events: Events) { this.loginForm = formBuilder.group({ userName: ['', Validators.compose([Validators.required])], password: ['', Validators.compose([Validators.required])] }); this.usercreds = { userName: '', password: '' } } login(){ if(this.loginForm.valid){ let loading = this.loadCtrl.create({ 'content':'Please Wait..', 'duration':1000, }); loading.present(); this.usercreds.name=this.loginForm.controls['userName'].value; this.usercreds.password = this.loginForm.controls['password'].value; console.log(this.usercreds); this.fd = new FormData(); this.fd.append("User[username]", this.loginForm.value.userName.trim() ); this.fd.append("User[password]", this.loginForm.value.password); this.authServiceProvider.login(this.fd).then(response => { //console.log(response['data'].id); if(response['errorCode'] == 0 ){ this.storage.set('login_active_id', response['data'].id); //console.log(response['data'].mobile_token_id); this.storage.set('accessToken', response['data'].mobile_token_id); this.storage.set('user_info', response['data']); this.events.publish('user:login'); this.saveUserToken(); } else{ this.showAlert("",response['msg']); } }).catch((ex)=>{ }); } else{ let toast = this.toastCtrl.create({ 'message':'Please enter login details', 'duration':1000 }); toast.present(); } } }
Next steps you have to put a logout menu in the same place where you display the login menu. Open the app.html file and try with this code.
<ion-menu [content]="content" side="right"> <ion-content class=menu-content> <!-- Menu Items in the Sidebar --> <ion-list no-lines > <div class="listSize"> <button menuClose ion-item> <ion-icon name="home"></ion-icon> Home </button> <button menuClose ion-item > <ion-icon name="train"></ion-icon> Products </button> <!-- After Login these Item will display in Menubar --> <button [hidden]="!login_check_id" menuClose ion-item > <ion-icon name="star"></ion-icon> My Package </button> <button [hidden]="!login_check_id" menuClose ion-item > <ion-icon name="paper"></ion-icon> My Product </button> </div> </ion-list> </ion-content> <ion-footer menuClose> <button [hidden]="login_check_id" ion-button (click)="goLoginPage()" full >Login</button> <button [hidden]="!login_check_id" ion-button (click)="goLogout()" full >Log Out</button> </ion-footer> </ion-menu>
Here you can also use the same click() function in the logout menu and give name logout() and Apply below function code:
this.events.publish('user:logout');
Now go to the app.component.ts file and generate a function in the constructor like that.
this.loginEvents();
Apply app.component.ts code:
import { Component, ViewChild } from '@angular/core'; import {Nav, Platform, AlertController, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { Storage } from '@ionic/storage'; import { HomePage } from '../pages/home/home'; import { ListPage } from '../pages/list/list'; import {LoginPage} from '../pages/login/login'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HomePage; pages: Array<{title: string, component: any}>; create: any; login:boolean=true; logout:boolean=false; MyPackage:boolean=false; MyProduct:boolean=false; login_check_id: boolean=false; constructor(public platform: Platform,private events: Events, private alertCtrl: AlertController, private storage: Storage,public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); this.pages = [ { title: 'Home', component: HomePage }, { title: 'List', component: ListPage }, { title: 'Login', component:LoginPage}, ]; this.listenToLoginEvents(); } @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = HomePage; create: any; login:boolean=true; logout:boolean=false; login_check_id: boolean=false; constructor(public platform: Platform,private events: Events, private alertCtrl: AlertController, private storage: Storage,public statusBar: StatusBar, public splashScreen: SplashScreen) { this.initializeApp(); this.pages = [ { title: 'Home', component: HomePage }, { title: 'List', component: ListPage }, { title: 'Login', component:LoginPage}, ]; this.LoginEvents(); } LoginEvents() { this.events.subscribe('user:login', () => { this.login_check_id = true; }); this.events.subscribe('user:logout', () => { this.login_check_id = false; }); } goLoginPage(){ this.nav.push(LoginPage); } goLogout() { let alert = this.alertCtrl.create({ title: 'Confirm logout', message: 'Are you sure?', buttons: [ { text: 'Cancel', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }, { text: 'Logout', handler: () => { this.storage.clear().then(() => { this.events.publish('user:logout'); this.nav.setRoot(HomePage); }); } } ] }); alert.present(); } }
Initially under the export class MyApp assign the login_check_id equal false.
login_check_id: boolean=false;
and outside the constructor define the function like this
LoginEvents() { this.events.subscribe('user:login', () => { this.login_check_id = true; }); this.events.subscribe('user:logout', () => { this.login_check_id = false; }); }
If you closely observe the code you can see that user is key and login or logout is the data which we have pass through the function. And when the value of a user is login then login_check_id is true or login_check_id is false.
If you want to hide some menu item’s before login just hide the button by change login_check_id is false.
Code is like
[hidden]="!login_check_id"
And here you have done all the things. You can simply save the pages and run the program
Initially, before login some menu item’s are hidden. After login automatically has a hidden menu item will display
in the menu bar.
Thank you for spending your valuable time.
Thank you for your post, I look for such article along time, today I find it finally. this post gives me lots of advise it is very useful for me.
We are happy to help you. Thanks for your valuable comment.