import { Injectable } from '@angular/core';
@Injectable() export class AlertService { message: string;
constructor() {}
setMessage(msg: string) { this.message = msg; }
getMessage() { return this.message; } }
import { Component, OnInit, HostListener } from '@angular/core'; import { AlertService } from './alert.service';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'custom-beforeunload-alert'; message: string;
constructor(private alertService: AlertService) {}
ngOnInit() { this.alertService.setMessage('确认离开吗?'); }
@HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) { const message = this.alertService.getMessage(); if (message) { $event.returnValue = message; } } }
{{alertService.getMessage()}}