首页 > 解决方案 > 单击角度 9 中页面的其他位置时隐藏通知

问题描述

我有一个在角度 9 中显示通知的模式。

我有一个显示或隐藏模式的按钮,它可以找到,但我需要点击页面的其他位置(不是显示/隐藏按钮)如果模式显示,隐藏它。

这是演示

html:

    <div class="header">
 <button (click)="toggleFunction()">show</button>
<div class="showButton" id="showNotification">
  <span>this is test</span>
</div>
</div>

ts:

   export class TopeheaderComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
    toggleFunction() {
        let element = document.getElementById('showNotification');
        if (element.style.display === '' || element.style.display === 'none') {
            element.style.display = 'block';
        } else if (element.style.display === 'block') {
            element.style.display = 'none';
        }
    }
}

我怎么解决这个问题 ?

标签: javascriptangulartypescript

解决方案


您可以HostListener用来检测目标元素外的点击

零件

  isHide: boolean = true;

  toggleFunction(e: MouseEvent) {
    e.stopPropagation();
    this.isHide = !this.isHide; // toggle the notification 
  }

  @HostListener("document:click") hideOnClick() {
    this.isHide = true;
  }

模板

<div class="header">
    <button (click)="toggleFunction($event)">show</button>
    <div class="showButton" [ngClass]="{'d-none':isHide}">
        <span>this is test</span>
    </div>
</div>

我只是更新了使用 ngClass 指令更新切换类的元素基础的逻辑,更易读更容易。 stopPropagation阻止事件冒泡,因此上层事件侦听器不会捕获此事件。

演示


推荐阅读