angular 路由发生改变时弹框提示是否离开
在表单输入页面,当表单信息未保存时,弹框提示是否保存,点击是,则离开,点击否则停留在当前页面
参考:https://blog.csdn.net/qq_39785489/article/details/79879915
angular 路由守卫 CanActivate和CanDeactivate
参考二:https://stackoverflow.com/questions/35922071/warn-user-of-unsaved-changes-before-leaving-page
路由离开和页面刷新都会有弹框提示
具体步骤参照:
1、在routing中
{ path: 'retailer-signup',canDeactivate:[UnfocusGuardService], component: RetailerSignUpComponent , data: { breadcrumb: 'Retailer Sign Up' }},
2、定义canDeactivate:(可以写入服务中)
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { RetailerSignUpComponent } from '../../pages/frontend/retailer-sign-up/retailer-sign-up.component';
import { CookieService } from 'ngx-cookie-service';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface CanComponentDeactivate {
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}
@Injectable()
export class UnfocusGuardService implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate() ?
true :
// NOTE: this warning message will only be shown when navigating elsewhere within your angular app;
// when navigating away from your angular app, the browser will show a generic warning message
// see http://stackoverflow.com/a/42207299/7307355
confirm('Information not saved. Are you sure you want to leave?');
}
}
3、component中:
export class RetailerSignUpComponent implements CanComponentDeactivate { @HostListener('window:beforeunload') canDeactivate(): Observable<boolean> | boolean { // insert logic to check if there are pending changes here; // returning true will navigate without confirmation // returning false will show a confirm dialog before navigating away if(this.registerGroupForm.dirty){ return false; }else{ return true; } } }

浙公网安备 33010602011771号