在 ionic 4 中只要加上 就可以很方便的让我们加上返回钮,但有的时候我们需要再返回前做一些检查,例如说页面上有一些资料变更了,但是使用者还没有储存,这时候如果提示一下,体验一定比较好!
直接看看如何实作,假设我们的页面叫做 profile,点击 back 的时候会跳 alert 提示要不要储存,profile.page.ts 如下
import {Component, OnInit, ViewChild} from '@angular/core';import {Router, NavigationExtras} from '@angular/router';import {AlertController, IonBackButtonDelegate, NavController} from '@ionic/angular';@Component({ selector: 'app-profile', templateUrl: './profile.page.html', styleUrls: ['./profile.page.scss'],})export class Profile implements OnInit { saveButton: any; @ViewChild(IonBackButtonDelegate, {static: false}) backButtonDelegate: IonBackButtonDelegate; constructor( private router: Router, private navCtrl: NavController, private alertController: AlertController, ) { // 纪录资料是否有变更 this.saveButton = false; } ngOnInit() { } ionViewDidEnter() { // 取得 back button 的 click event this.backButtonDelegate.onClick = () => { console.log('leave'); if (this.saveButton === true) { this.presentDeleteConfirm(); } else { this.navCtrl.pop(); } }; } async presentDeleteConfirm() { const alert = await this.alertController.create({ header: 'Confirm!', message: '资料未储存?', buttons: [ { text: '离开', role: 'cancel', cssClass: 'secondary', handler: (blah) => { console.log('Confirm Cancel: blah'); this.navCtrl.pop(); } }, { text: '储存', handler: () => { } } ] }); await alert.present(); }}
html 记得加上按钮
<ion-header> <ion-toolbar> <ion-title>quiz-edit</ion-title> <ion-buttons slot="start"> <ion-back-button></ion-back-button> </ion-buttons> <ion-buttons [ngStyle]="{'color': saveButtonStyle == true ? 'red' : ''}" (click)="submitProfile()" slot="end"> 储存 </ion-buttons> </ion-toolbar></ion-header></ion-header>
这样就可以啰,看看效果,特别注意这个方法对 Android 手机上的返回按钮无效喔!