首页 > 解决方案 > 无法在角度指令中删除事件监听器

问题描述

当我按 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;
  }
}

任何的想法?

标签: angularangular-directive

解决方案


使用反应式方法更容易实现这一点:

@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 秒它确实捕获了事件并阻止了刷新。5s后可以刷新页面:

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

要尝试它,您必须使用:

在此处输入图像描述

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


推荐阅读