首页 > 解决方案 > Angular - 选择选项卡时重新加载页面?

问题描述

当用户单击我的 Angular 应用程序的浏览器选项卡时,有没有办法触发重新加载页面的功能?

我相信这将通过 window.location.reload() 来完成,但我不确定如何在选项卡选择时触发这一行。

我认为这可以通过使 body/html 具有“onfocus='reloadPage()'”属性来完成,但我不希望它在我在页面上移动鼠标时刷新 500 次,只是一旦将选项卡聚焦/单击时。

标签: cssangulartypescriptbrowserreload

解决方案


我喜欢@enjoibp3 解决方案,但不是添加事件侦听器并删除它们。你最好使用@HostListener文档

import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  @HostListener('window:focus') onFocus() {
    console.log('window focus');

    window.location.reload();
  }
}

在此处查看 stackblitz 代码示例和此处的演示项目


推荐阅读