angular - 无法在角度指令中删除事件监听器
问题描述
当我按 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;
}
}
任何的想法?
解决方案
使用反应式方法更容易实现这一点:
@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 应用程序,而不是应用程序本身
推荐阅读
- python - 任务卡在 Celery 队列中
- node.js - 续集关联不起作用,如何解决?
- typescript - 如何使用 angular 2+ 使用 get 方法传递身体?
- mongodb - 使用关联的集合字段进行查找和排序的 MongoDB 聚合正在减慢查询速度
- python - 无法在 python 中与 Flask 连接
- javascript - 为特定子组件反应 propTypes
- python-3.x - 根据数据框中给出的值从 SQL 中检索数据
- python - Python:将字符串列表转换为空/无的浮点数
- azurekinect - 如何关闭 Azure Kinect、边框和飞行像素的深度过滤器?
- python - 安装 keras 和 tensorflow 后 Python 崩溃了