多个DOMS的Angular 6模糊事件

时间:2018-10-10 07:18:11

标签: angular blur

我有一个按钮,应该显示一个单独的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连接到用于模糊事件的按钮吗?

1 个答案:

答案 0 :(得分:2)

在这些情况下,我会制定一条指令,它们整洁且可重复使用,通过谷歌搜索“单击外部指令angular”,您可以找到一些答案。在这里,尽管您需要注意两个元素,所以该指令不会那么整洁,但是下面的方法可以工作。

为按钮提供一些类名,例如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中使用它:

<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