【问题标题】:How do I get a reference to the window object within an Angular 5 Component如何在 Angular 5 组件中获取对窗口对象的引用
【发布时间】:2018-07-09 07:20:52
【问题描述】:

我是 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】:

    你可以像这样使用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() {}
    }
    

    【讨论】:

    • 感谢您的帮助,但不幸的是,当我收到离开页面/停留在页面模式对话框并按下停留在页面按钮时,这些主机监听器似乎没有在 Firefox 中被触发。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多