如何捕捉动作 window:beforeunload Angular 8

How to capture anctions window:beforeunload Angular 8

我对 Angular 应用中的 window 事件 beforeunload 有疑问。 我想检查用户是否导航到另一个页面,如果是这样我想清理 sessionStorage。我用。

   onBeforeUnload(event: BeforeUnloadEvent) {
       event.returnValue = '';
   }

Beforeunload 事件也用作页面刷新。如何检查用户是否离开应用程序并在确认对话框后清除会话存储。

您可以在组件的构造函数中尝试以下代码 class。

选项 1

window.addEventListener("beforeunload", function (e) {
   exampleService.logout();
});

选项 2

 @HostListener('window:beforeunload', ['$event'])
     beforeUnloadHandler(event: any) {
     event.preventDefault();
     // any other code / dialog logic
 }

To distinguish from 2 cases, you should check out this Whosebug question or related questions, here's one:

Question

希望,这对您有所帮助。

下面的代码会让浏览器询问用户是否要丢失未保存的更改。

此外,我正在检查表单是否有问题。

如果表单不脏,浏览器不会打扰用户并关闭它。

import { Component, ViewChild, HostListener } from '@angular/core';
import { NgForm } from '@angular/forms';
import { DetailedUser } from 'src/app/models/detailed-user';

@Component({
  selector: 'app-member-edit',
  templateUrl: './member-edit.component.html',
  styleUrls: ['./member-edit.component.css']
})
export class MemberEditComponent {
  user: DetailedUser = new DetailedUser();
  @ViewChild('userForm') userForm: NgForm;
  @HostListener('window:beforeunload', ['$event'])
  WindowBeforeUnoad($event: any) {

    if (this.userForm.dirty) {
      $event.returnValue = 'Your data will be lost!';
    }
  }
  saveChanges(){
    ....
    this.userForm.reset(this.user);
  }
}

以下是html部分

     <form (ngSubmit)="saveChanges()" #userForm="ngForm">
        <div class="form-group">
          <label for="introduction">Introduction</label>
          <textarea
            name="introduction"
            class="form-control"
            [(ngModel)]="user.introduction"
            rows="6"></textarea>
        </div>
        <div class="form-group">
          <label for="lookingFor">Looking For</label>
          <textarea
            name="lookingFor"
            class="form-control"
            [(ngModel)]="user.lookingFor"
            rows="6"></textarea>
        </div>
      </form>