onSubmit(value: string): void { 
  if(this.authForm.valid) {

  	// This is an easy example, so we're not going to check if authorization was successful

  	window.localStorage.setItem('username', value.username);
  	window.localStorage.setItem('password', value.password);

    this.nav.push(HomePage);	    	
  }
}
 
So far so good. On the next page, we will show a welcome message:
 
this.username = window.localStorage.getItem('username'); 
 
<h1>Welcome {{username}}</h1>
 
Unfortunately, there’s one problem. Because we made a transition between FormPage and HomePage, application will show a back button. This is something we want to avoid. There’s only one case when we want to allow back functionality, and that’s when a user clicks Log Out button.
 
To hide back button, add hideBackButton keyword to HomePage NavBar component:
 
<ion-navbar hideBackButton *navbar>
    <ion-title>
        HomePage
    </ion-title>
</ion-navbar>
 
If we close this application and open it again, because stored user data exists, app.js will navigate us back to the HomePage.
 
What will happen, if we click on a Log Out button, and we are navigated back to the FormPage again? We will indeed witness a transition, but HomePage will stay in a navigation stack (navigation history). For example, if we click on a back button (Android, this will thankfully not work on iOS) we will navigate back to the HomePage. Again, this is something we want to avoid.
 
We will first remove username and password stored in local storage. Next, we will set FormPage as a root page and pop directly to it, thus cleaning existing navigation history:
 
logout(): void { 
	window.localStorage.removeItem('username');
	window.localStorage.removeItem('password');

	this.nav.setRoot(FormPage);
  this.nav.popToRoot();   
}  
 
If we restart our app again, teh root component will navigate us to the FormPage.
 

Source Code

 
In case GitHub repo is not available, and you can only use code provided below, this is what project folder looks like (image taken from Sublime text editor):
 
Ionic 2 Simple Authorization Project Structure
 
I’ll show you only relevant files; everything else is available in provided GitHub repo.
 
app.js
import {App, Platform, Config} from 'ionic/ionic';
import {FormPage} from './pages/form/form';
import {HomePage} from './pages/home/home';

@App({
  templateUrl: 'build/app.html'
})
export class MyApp {
  constructor(platform: Platform) {
    this.platform = platform;
    this.initializeApp();
    this.checkPreviousAuthorization();    
  }

  initializeApp() {
    this.platform.ready().then(() => {
      console.log('Platform ready');
    });
  }

  checkPreviousAuthorization(): void { 
    if((window.localStorage.getItem('username') === "undefined" || window.localStorage.getItem('username') === null) && 
       (window.localStorage.getItem('password') === "undefined" || window.localStorage.getItem('password') === null)) {
      this.root = FormPage;
    } else {
      this.root = HomePage;
    }
  }   
}
 
form.js
import { Page, NavController } from 'ionic/ionic';
import { Component } from 'angular2/core';  
import { HomePage } from '../home/home';
import { FORM_DIRECTIVES, FormBuilder,  ControlGroup, Validators, AbstractControl } from 'angular2/common';


@Page({
	templateUrl: 'build/pages/form/form.html',
	directives: [FORM_DIRECTIVES]
})

export class FormPage {

	authForm: ControlGroup;
	username: AbstractControl;
	password: AbstractControl;

	constructor(fb: FormBuilder, nav: NavController) {
		this.nav = nav;

	   	this.authForm = fb.group({  
	    	'username': ['', Validators.compose([Validators.required, Validators.minLength(8), checkFirstCharacterValidator])],
	    	'password': ['', Validators.compose([Validators.required, Validators.minLength(8), checkFirstCharacterValidator])]
	    });

		this.username = this.authForm.controls['username'];	    
		this.password = this.authForm.controls['password'];		
	}

	onSubmit(value: string): void { 
	    if(this.authForm.valid) {

	    	// This is an easy example, so we're not going to check if authorization was successful

	    	window.localStorage.setItem('username', value.username);
	    	window.localStorage.setItem('password', value.password);

		    this.nav.push(HomePage);	    	
	    }
	} 

	function checkFirstCharacterValidator(control: Control): { [s: string]: boolean } {  
		if (control.value.match(/^\d/)) {  
			return {checkFirstCharacterValidator: true};  
		}		
	}
}
 
form.html
<ion-navbar *navbar>
  <ion-title>
    Authorization
  </ion-title>
</ion-navbar>

<ion-content class="home" padding>
  <form [ngFormModel]="authForm" (ngSubmit)="onSubmit(authForm.value)">
    <ion-item [class.error]="!username.valid && username.touched">
      <ion-label floating>Username</ion-label>
      <ion-input type="text" value="" [ngFormControl]="username"></ion-input>         
    </ion-item>
    <div *ngIf="username.hasError('required') && username.touched"  
        class="error-box">* Username is required!</div>
    <div *ngIf="username.hasError('minlength') && username.touched"  
        class="error-box">* Minimum username length is 8!</div>            
    <div *ngIf="username.hasError('checkFirstCharacterValidator') && username.touched"  
        class="error-box">* Username cant't start with number!</div>                       
    <ion-item floating-label [class.error]="!password.valid && password.touched">
      <ion-label floating>Password</ion-label>
      <ion-input type="text" value="" [ngFormControl]="password" ></ion-input>
    </ion-item>
    <div *ngIf="password.hasError('required') && password.touched"  
        class="error-box">* Password is required</div>    
    <div *ngIf="password.hasError('minlength') && password.touched"  
        class="error-box">* Minimum password length is 8!</div>                     
    <div *ngIf="password.hasError('checkFirstCharacterValidator') && password.touched"  
        class="error-box">* Password cant't start with number!</div>             
    <br/><br/> 
    <button type="submit" class="custom-button" [disabled]="!authForm.valid" block>Submit</button>
  </form>
</ion-content>
 
home.js
import { Page, NavController, NavParams } from 'ionic/ionic';
import { Component } from 'angular2/core';  
import { FormPage } from '../form/form';


@Page({
	templateUrl: 'build/pages/home/home.html'
})

export class HomePage {

	constructor(nav: NavController, navParams: NavParams) {
	  this.nav = nav;
	  this.username = window.localStorage.getItem('username');   
	}

	logout(): void { 
  	window.localStorage.removeItem('username');
  	window.localStorage.removeItem('password');

		this.nav.setRoot(FormPage);
	  this.nav.popToRoot();   
	} 
}
 
home.html
<ion-navbar hideBackButton *navbar>
  <ion-title>
    HomePage
  </ion-title>
</ion-navbar>

<ion-content class="home" padding>
  <h1>Welcome {{username}}</h1>
  <button type="button" class="custom-button" block (click)="logout()">Log Out</button>
</ion-content>
 

Deployment

 
Next step, build our application:
 
ionic build android
 
Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.
 
Finally:
 
ionic run android -l -c -s
 

Download The Code

 
Working GitHub repo link can be found below:
 
GitHub
 
 

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.

Blogs worth reading

If you're here looking for information related to the Ionic Framework, you will also like these blogs:






  • justin

    How can we integrate firebase simple login with this that is not twitter

  • jkjaskaran

    Does window.localstorage something works in ionic 2 or have they replaced it with ionic native LocalStorage

  • ariful alam

    hello,
    without showing form page, its directly showing home page and when click on logout button that showing logout() is not a function in console.

    regards

  • Johnny FirstShoe

    All I get is a blank screen? Has ionic 2 changed?