我是Angular第5版的新手并参考了以下文章:
https://juristr.com/blog/2016/09/ng2-get-window-ref/
我试图访问window.onbeforeunload
和window.onfocus
我已经完成了本文并创建了一个新服务,但现在在我需要访问window.onbeforeunload
和window.onfocus
的实际组件中,我不知道如何合并以下函数:
window.onbeforeunload = function(){
userWantsToLeave = true;
console.log("onbeforeunload: ",userWantsToLeave);
};
window.onfocus = function() {
if(userWantsToLeave) {
userWantsToLeave = false;
console.log("onfocus: ",userWantsToLeave);
}
}
在我的组件中,我可以同时使用所附的文章同时实现上述两个功能吗?
我只需要能够在我的组件中访问这两个窗口函数。
你可以像这样使用HostListener
。
import { Component , HostListener } from '@angular/core';
export class AppComponent {
@HostListener('window:beforeunload', ['$event'])
doSomething($event) {
/// code
}
@HostListener('window:focus', ['$event'])
dofocus($event) {
/// code
}
constructor() {}
}