Angular 6: 页面离开时的简单确认
创始人
2024-10-16 06:00:43
0

在Angular 6中,可以通过使用CanDeactivate守卫来实现页面离开时的确认。以下是一个包含代码示例的解决方法:

首先,创建一个名为confirm-dialog.component.ts的确认对话框组件,该组件将显示一个确认消息并返回一个Promise,以便在用户确认或取消时进行解析:

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-confirm-dialog',
  template: `
    

确认离开

您确定要离开此页面吗?

` }) export class ConfirmDialogComponent { @Output() confirmed = new EventEmitter(); confirm() { this.confirmed.emit(true); } cancel() { this.confirmed.emit(false); } }

接下来,在需要进行确认的组件中,例如home.component.ts,实现CanDeactivate接口,并在canDeactivate方法中弹出确认对话框:

import { Component, OnInit } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';
import { ConfirmDialogComponent } from './confirm-dialog.component';

@Component({
  selector: 'app-home',
  template: `
    

首页

` }) export class HomeComponent implements OnInit, CanDeactivate { canDeactivate(component: ConfirmDialogComponent): Observable | boolean { return component.confirmed; } navigateToAbout() { // 导航到关于页面 } ngOnInit() { // 添加页面离开的确认 window.onbeforeunload = () => { return !this.canDeactivate(new ConfirmDialogComponent()); }; } }

最后,在路由配置中,为HomeComponent指定canDeactivate守卫:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';

const routes: Routes = [
  { path: '', component: HomeComponent, canDeactivate: [HomeComponent] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

这样,当用户尝试离开HomeComponent时,将会弹出确认对话框,只有在用户确认时才会导航到下一个页面。

相关内容

热门资讯

玩家必看教程!wepoker买... 玩家必看教程!wepoker买钻石有用吗,werplan怎么作弊,AI教程(有挂教程);致您一封信;...
如何分辨真伪!wepoker怎... 此外,数据分析德州(wepoker怎么设置透视)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
必备教程!xpoker辅助神器... 必备教程!xpoker辅助神器,wepoker辅助器有哪些功能,科技教程(有挂方法);致您一封信;亲...
科技通报!aapoker破解侠... 科技通报!aapoker破解侠是真的吗,epoker透视,介绍教程(有挂神器)关于aapoker破解...
推荐十款!约局吧透视挂下载,约... 推荐十款!约局吧透视挂下载,约局吧德州真的有透视挂吗,扑克教程(有挂神器)准备好在约局吧德州真的有透...
攻略讲解!pokemmo手机版... 攻略讲解!pokemmo手机版脚本,hhpoker透视脚本视频,解密教程(有挂软件)是一款可以让一直...
分享实测!wepoker有什么... 分享实测!wepoker有什么规律,hardrock作弊,可靠教程(有挂软件)是由北京得wepoke...
交流学习经验!wepoker底... 交流学习经验!wepoker底牌透视,wepoker网页版透视方法,存在挂教程(有挂教程)关于wep...
发现玩家!德普之星辅助器,we... 1、发现玩家!德普之星辅助器,wepoker手机插件,曝光教程(有挂技巧);详细教程。2、德普之星辅...
一起来讨论!德州局透视脚本免费... 一起来讨论!德州局透视脚本免费版下载手机版,wepoker私人局俱乐部,AA德州教程(有挂技巧);致...