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时,将会弹出确认对话框,只有在用户确认时才会导航到下一个页面。

相关内容

热门资讯

5分钟辅助!约局吧德州真的有透... 5分钟辅助!约局吧德州真的有透视挂吗,we-poker软件,妙计教程(今日头条)约局吧德州真的有透视...
第九分钟辅助!wpk插件,hh... 第九分钟辅助!wpk插件,hh poker辅助有用吗,资料教程(确实有挂)1、首先打开hh poke...
第三分钟辅助!wepoker透... 第三分钟辅助!wepoker透视脚本苹果版,pokemmo辅助器,教程书教程(确实有挂)1、完成we...
第三分钟辅助!哈糖大菠萝能开挂... 第三分钟辅助!哈糖大菠萝能开挂吗,aapoker脚本,法门教程(有人有挂)1、超多福利:超高返利,海...
两分钟辅助!wepoker游戏... 两分钟辅助!wepoker游戏的安装教程,wepoker透视苹果系统,法子教程(确实有挂)1、这是跨...
七分钟辅助!德扑之心免费透视,... 七分钟辅助!德扑之心免费透视,wepoker私人辅助器,方案教程(有挂教学)1、德扑之心免费透视免费...
三分钟辅助!hhpoker可以... 三分钟辅助!hhpoker可以开挂吗,wepoker私人局透视教程,操作教程(有挂讲解)1、wepo...
4分钟辅助!wepoker辅助... 4分钟辅助!wepoker辅助工具,hhpoker透视方法,教程书教程(有挂教程)1、起透看视 we...
9分钟辅助!wepoker怎么... 9分钟辅助!wepoker怎么获得好牌,pokerworld破解版下载,练习教程(有挂分析)1、不需...
第九分钟辅助!拱趴大菠萝挂怎么... 第九分钟辅助!拱趴大菠萝挂怎么安装,pokemmo手机版脚本免费,机巧教程(有挂讲解)1、上手简单,...