无法删除角度指令中的EventListener

问题描述 投票:1回答:1

我试图防止按f5键重新加载整个页面。我创建了一条指令,当按f5时单击一个按钮,此指令有效,但是我无法删除此事件

https://stackblitz.com/edit/angular-wpok2b

HTML:

<button appClickf5 disabled *ngIf="show">will be clicked if f5</button>
<br/><br/><br/>
<button (click)="show = !show">toggle init/destroy</button>
<div id="output"></div>

指令:

import { Directive, ElementRef, OnDestroy, OnInit } from '@angular/core';

@Directive({
  selector: '[appClickf5]'
})
export class Clickf5Directive  implements OnInit, OnDestroy {

  constructor(private _el: ElementRef) { }

  ngOnInit() {
    this.log("init")
    document.addEventListener("keydown", this.callback.bind(this));
  }

  ngOnDestroy() {
    this.log("ngOnDestroy")
    document.removeEventListener("keydown", this.callback.bind(this));
  }

  callback(e: KeyboardEvent) {
    if ((e.code === "F5" || e.key === "F5") && e.ctrlKey === false) {
      e.preventDefault();
      this._el.nativeElement.click();
      this.log("element clicked");
    }
  }

  private log(txt){
    document.getElementById("output").innerHTML+="<br/>"+txt;
  }
}

任何想法?

angular angular-directive
1个回答
2
投票

通过反应性方法更容易实现:

@Directive({
  selector: '[appClickf5]',
})
export class Clickf5Directive implements OnInit, OnDestroy {
  private destroyed$: Subject<void> = new Subject();

  constructor(private _el: ElementRef) {}

  public ngOnInit() {
    fromEvent(document, 'keydown').pipe(
      filter(
        (e: KeyboardEvent) =>
          (e.code === 'F5' || e.key === 'F5') && e.ctrlKey === false
      ),
      tap((e: KeyboardEvent) => {
        e.preventDefault();
        this._el.nativeElement.click();
      }),
      takeUntil(this.destroyed$)
    ).subscribe();
  }

  public ngOnDestroy() {
    this.destroyed$.next();
    this.destroyed$.complete();
  }
}

我仅使用rxjs进行了现场演示,在开始的5秒钟内,它确实捕获了事件并阻止了刷新。 5秒后,您可以刷新页面:

https://stackblitz.com/edit/rxjs-rfylfi?file=index.ts

要尝试,您必须使用:

enter image description here

否则,将重新加载stackblitz应用程序,而不是应用程序本身

© www.soinside.com 2019 - 2024. All rights reserved.