如何在Angular 5 Component中获取对窗口对象的引用

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

我是Angular第5版的新手并参考了以下文章:

https://juristr.com/blog/2016/09/ng2-get-window-ref/

我试图访问window.onbeforeunloadwindow.onfocus

我已经完成了本文并创建了一个新服务,但现在在我需要访问window.onbeforeunloadwindow.onfocus的实际组件中,我不知道如何合并以下函数:

window.onbeforeunload = function(){
  userWantsToLeave = true;
  console.log("onbeforeunload: ",userWantsToLeave);
};

window.onfocus = function() {
  if(userWantsToLeave) {
    userWantsToLeave = false;
    console.log("onfocus: ",userWantsToLeave);
  }
}

在我的组件中,我可以同时使用所附的文章同时实现上述两个功能吗?

我只需要能够在我的组件中访问这两个窗口函数。

angular typescript
1个回答
2
投票

你可以像这样使用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() {}
}
© www.soinside.com 2019 - 2024. All rights reserved.