Skip to content

Instantly share code, notes, and snippets.

@vrdriver
Created April 29, 2018 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrdriver/2ffa221a9ff22be2ecf634cffbef44c0 to your computer and use it in GitHub Desktop.
Save vrdriver/2ffa221a9ff22be2ecf634cffbef44c0 to your computer and use it in GitHub Desktop.
An Ionic Cordova AngularJS back button working on the TABS example
import { Component, ViewChild } from '@angular/core';
import { App, Platform, AlertController } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { TabsPage } from '../pages/tabs/tabs';
import { WelcomePage } from '../pages/welcome/welcome';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
@Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage = TabsPage;
@ViewChild('root') navCtrl: NavController;
constructor(public platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public app: App,
public alertCtrl: AlertController
)
{
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
// https://www.gajotres.net/ionic-2-3-how-to-manage-hardware-back-button-event-like-a-pro/2/
let nav = app.getActiveNavs()[0];
platform.registerBackButtonAction(() =>
{
let nav = app.getActiveNavs()[0];
let activeView = nav.getActive();
if((activeView.name === "WelcomePage") || (activeView.name === "AboutPage") || (activeView.name === "HomePage") || (activeView.name === "ContactPage"))
{
if (nav.canGoBack()){ //Can we go back?
nav.pop();
} else {
const alert = this.alertCtrl.create({
title: 'App termination',
message: 'Do you want to close the app?',
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Application exit prevented!');
}
},{
text: 'Close App',
handler: () => {
this.platform.exitApp(); // Close this application
}
}]
});
alert.present();
}
} else
{
if (nav.canGoBack())
{ //Can we go back?
nav.pop();
}
}
});
});
}
}
@vrdriver
Copy link
Author

This example was originally taken from here
https://www.gajotres.net/ionic-2-3-how-to-manage-hardware-back-button-event-like-a-pro/2/
https://github.com/Gajotres/IonicBackButtonHandleExample/blob/master/src/app/app.component.ts

But I needed a little something extra, as the back button just didn't work as expected.
If you navigated to all the different tabs, the back button would only work on the "HomePage". It felt like the app just wasn't working.
So, this at least gives you the option to quit if you are on any of the defined tab pages that you set.

I also added this to the original author's 'bug' tracker. Not as a bug, but a suggestion/thankyou.
Gajotres/IonicBackButtonHandleExample#2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment