how to go back to previous screen ionic 2

hybrid Dev picture hybrid Dev · Apr 29, 2017 · Viewed 31.2k times · Source

In ionic q we will use $ionichistory.goback()to go back the previous screen. But in ionic 2 how can we achive that. And i tried this button on click to print the console message . But its not working.

<ion-buttons left class="loginnavbtn" (click)="goback()">
  CANCEL
</ion-buttons>

.js

goback() {
   console.log('Click on button Test Console Log');
}

Please help me out. i have two screen . when i go from first screen to next screen. in next screen i have one button called back. When i press that i should be back to first screen. how to so that ?

My full code :

html:

<ion-header>
  <!-- use ion-toolbar for a normal toolbar and ion-navbar for navigation -->
  <ion-toolbar>
    <ion-buttons left class="loginnavbtn" (click)="goback()">

    CANCEL
    <!-- left aligned content here -->
    </ion-buttons>

    <ion-title>
      LOGIN
    </ion-title>

    <ion-buttons right class="loginnavbtn" (click)="loginbtntap()">
    SAVE
      <!-- left aligned content here -->
    </ion-buttons>
  </ion-toolbar>
</ion-header>
<ion-content>


   </ion-content>

my .js :

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';



@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})

export class LoginPage {


 goback() {
    this.navCtrl.pop();
}
loginbtntap() {
    this.navCtrl.pop();
}

  constructor(private navCtrl:NavController) {



  }

}

my .scss:

page-login {
ion-header {
  .button-md {
    box-shadow: none;
  }

  .toolbar-title {
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;
    font-size: 15px;
    font-weight: 500;
  }
}

.loginnavbtn {

  color: #116096 !important;
   font-size: 14px;
    font-weight: 400;
}
}

Answer

Suraj Rao picture Suraj Rao · Apr 29, 2017

Check NavController API in the docs.

To go to previous page,inject navcontroller in the constructor and call pop().

constructor(private navCtrl:NavController){}

goback() {
   this.navCtrl.pop();
   console.log('Click on button Test Console Log');
}

Also check syntax for button.

<ion-buttons >
    <button ion-button left class="loginnavbtn" (click)="goback()">
      Cancel
    </button>
    <!-- left aligned content here -->
    </ion-buttons>