Angular 6 多个 DOMS 的模糊事件
Angular 6 Blur Event for multiple DOMS
我有一个按钮应该显示一个单独的 div。
如果我单击 div 以外的任何其他内容,div 应该会消失。
我试图用模糊来做到这一点,但如果我点击我的按钮以外的任何东西(如果我点击我的 div),div 就会消失。
<button mat-button (click)="open=true;" (blur)="open=false;"></button>
<div *ngIf="open">content</div>
我想要的是:
1) 单击按钮 -> div 出现
2) 单击 div 内的元素(例如输入)并与之交互
3) 点击其他任何东西 -> div 消失
在其他页面上有人提到使用 tabindex="0" 但我不知道如何使用它。
是否可以将 div 连接到模糊事件的按钮?
在这些情况下,我会制定一个指令,它们简洁且可重复使用,通过谷歌搜索 "click outside directive angular" 您可以找到一些答案。在这里,虽然您需要观察两个元素,因此该指令不会那么简洁,但以下是有效的。
给您的按钮一些 class 名称,例如 open-button
。我们将在我们的指令中使用它。因此,按如下方式制定指令(并在声明数组中标记):
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[isOutside]'
})
export class IsOutsideDirective {
constructor(private elementRef: ElementRef) { }
@Output()
public isOutside = new EventEmitter();
// watch for click events
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
if (this.elementRef) {
// see if clicked element is the target element OR the button
const clickedInside = this.elementRef.nativeElement.contains(targetElement) ||
targetElement.classList.contains('open-button');
if (!clickedInside) {
this.isOutside.emit(true);
}
}
}
}
然后在你想要的 div 中使用它 hide/show:
<div *ngIf="open" (isOutside)="hide($event)" ....
hide()
然后会将 open
设置为 false
,因为 isOutside
仅在这两个元素之外单击时才会发出:
hide(event) {
this.open = false;
}
您的按钮也将切换 open
:
<button class="open-button" (click)="open = true">Show div</button>
演示:StackBlitz
我有一个按钮应该显示一个单独的 div。 如果我单击 div 以外的任何其他内容,div 应该会消失。 我试图用模糊来做到这一点,但如果我点击我的按钮以外的任何东西(如果我点击我的 div),div 就会消失。
<button mat-button (click)="open=true;" (blur)="open=false;"></button>
<div *ngIf="open">content</div>
我想要的是:
1) 单击按钮 -> div 出现
2) 单击 div 内的元素(例如输入)并与之交互
3) 点击其他任何东西 -> div 消失
在其他页面上有人提到使用 tabindex="0" 但我不知道如何使用它。 是否可以将 div 连接到模糊事件的按钮?
在这些情况下,我会制定一个指令,它们简洁且可重复使用,通过谷歌搜索 "click outside directive angular" 您可以找到一些答案。在这里,虽然您需要观察两个元素,因此该指令不会那么简洁,但以下是有效的。
给您的按钮一些 class 名称,例如 open-button
。我们将在我们的指令中使用它。因此,按如下方式制定指令(并在声明数组中标记):
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[isOutside]'
})
export class IsOutsideDirective {
constructor(private elementRef: ElementRef) { }
@Output()
public isOutside = new EventEmitter();
// watch for click events
@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
if (this.elementRef) {
// see if clicked element is the target element OR the button
const clickedInside = this.elementRef.nativeElement.contains(targetElement) ||
targetElement.classList.contains('open-button');
if (!clickedInside) {
this.isOutside.emit(true);
}
}
}
}
然后在你想要的 div 中使用它 hide/show:
<div *ngIf="open" (isOutside)="hide($event)" ....
hide()
然后会将 open
设置为 false
,因为 isOutside
仅在这两个元素之外单击时才会发出:
hide(event) {
this.open = false;
}
您的按钮也将切换 open
:
<button class="open-button" (click)="open = true">Show div</button>
演示:StackBlitz