javascript - 单击角度 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';
}
}
}
我怎么解决这个问题 ?
解决方案
您可以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
阻止事件冒泡,因此上层事件侦听器不会捕获此事件。
推荐阅读
- php - yii 中的 foreach 创建命令
- azure-active-directory - 从外部公司网络限制登录 Office 365
- django - 支持多个请求 - django API 后端
- javascript - 如何获得最接近的结果?
- python - Pandas:如何提取和计算数据框中每行的“小时”数
- python - Python:得到“分配前引用的局部变量'idx'的错误语句”
- python - 那个国家的背景是怎样形成的?(情节)
- typescript - Vue typescript 导入依赖
- html - 调整窗口大小时如何裁剪图像 HTML/CSS
- java - 使用 Selenium Web Driver 运行测试脚本 Page Object Model 时发生 java.lang.NullPointerException 异常