【发布时间】:2020-01-30 09:43:15
【问题描述】:
我试图阻止在按 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;
}
}
有什么想法吗?
【问题讨论】: