检测Angular组件外部的单击


Answers:


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

@Component({
  selector: 'selector',
  template: `
    <div>
      {{text}}
    </div>
  `
})
export class AnotherComponent {
  public text: String;

  @HostListener('document:click', ['$event'])
  clickout(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
    } else {
      this.text = "clicked outside";
    }
  }

  constructor(private eRef: ElementRef) {
    this.text = 'no clicks yet';
  }
}

工作示例-单击此处


13
当触发器元素内有一个由ngIf控制的元素时,此操作不起作用,因为ngIf从DOM中删除该元素的操作发生在click事件之前:plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
J. Frankenstein

它对通过以下方式动态创建的组件起作用吗:const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
阿维·莫拉利

1
有关这个主题的一个很好的文章:christianliebel.com/2016/05/...
米格尔·拉腊

47

替代AMagyar的答案。当您单击使用ngIf从DOM中删除的元素时,此版本有效。

http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview

  private wasInside = false;
  
  @HostListener('click')
  clickInside() {
    this.text = "clicked inside";
    this.wasInside = true;
  }
  
  @HostListener('document:click')
  clickout() {
    if (!this.wasInside) {
      this.text = "clicked outside";
    }
    this.wasInside = false;
  }


这也非常适合ngif或动态更新
Vikas Kandari

这太棒了
Vladimir Demirev '19

23

通过@Hostlistener绑定到文档单击非常昂贵。如果您过度使用它,将会并且将会产生明显的性能影响(例如,在构建自定义下拉组件时,您在表单中创建了多个实例)。

我建议在主应用程序组件内仅将一次@Hostlistener()添加到文档单击事件。该事件应将单击的目标元素的值压入存储在全局实用程序服务中的公共主题内。

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {

  constructor(private utilitiesService: UtilitiesService) {}

  @HostListener('document:click', ['$event'])
  documentClick(event: any): void {
    this.utilitiesService.documentClickedTarget.next(event.target)
  }
}

@Injectable({ providedIn: 'root' })
export class UtilitiesService {
   documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}

谁对单击的目标元素感兴趣,请订阅我们的公用事业服务的公共主题,并在组件被破坏时退订。

export class AnotherComponent implements OnInit {

  @ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef

  constructor(private utilitiesService: UtilitiesService) { }

  ngOnInit() {
      this.utilitiesService.documentClickedTarget
           .subscribe(target => this.documentClickListener(target))
  }

  documentClickListener(target: any): void {
     if (this.somePopup.nativeElement.contains(target))
        // Clicked inside  
     else
        // Clicked outside
  }

4
我认为这个应该成为公认的答案,因为它可以进行许多优化:例如在此示例中
edoardo849

这是我在互联网上获得的最漂亮的解决方案
Anup Bangale,

1
@lampshade正确。我谈到了这一点。再次阅读答案。我将取消订阅实现保留为您的样式(takeUntil(),Subscription.add())。别忘了退订!
ginalx

@ginalx我实现了您的解决方案,它可以按预期工作。虽然我使用它的方式遇到了问题。这是问题,请看一下
Nilesh

6

上面提到的答案是正确的,但是如果您失去了相关组件的关注之后却进行了繁重的工作,该怎么办。为此,我提供了一个带有两个标志的解决方案,其中仅当仅从相关组件中失去焦点时,才会进行聚焦事件处理。

isFocusInsideComponent = false;
isComponentClicked = false;

@HostListener('click')
clickInside() {
    this.isFocusInsideComponent = true;
    this.isComponentClicked = true;
}

@HostListener('document:click')
clickout() {
    if (!this.isFocusInsideComponent && this.isComponentClicked) {
        // do the heavy process

        this.isComponentClicked = false;
    }
    this.isFocusInsideComponent = false;
}

希望这会帮助你。纠正我,如果错过了任何事情。



2

ginalx的答案应设置为默认的一个imo:此方法可进行许多优化。

问题

假设我们有一个项目列表,并且在每个项目上我们都想包含一个需要切换的菜单。我们在按钮上添加了一个切换按钮,用于监听click自身事件(click)="toggle()",但是我们也想在用户单击菜单之外的任何时候切换菜单。如果项目列表增加并且我们@HostListener('document:click')在每个菜单上都附加了一个,则即使关闭菜单,该项目中加载的每个菜单也将开始监听整个文档的单击。除了明显的性能问题之外,这也是不必要的。

例如,您可以在通过点击切换弹出窗口时进行订阅,然后才开始监听“外部点击”。


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

并且,在*.component.html


<button (click)="toggle()">Toggle the menu</button>

尽管我同意您的想法,但建议不要将所有逻辑都塞在tap运算符中。而是使用 skipWhile(() => !this.isActive), switchMap(() => this._utilitiesService.documentClickedTarget), filter((target) => !this._elementRef.nativeElement.contains(target)), tap(() => this._toggleMenuSubject$.next(false))。这样,您可以利用更多的RxJ,并跳过一些订阅。
吉兹拉(Gizrah)

0

改善@J。科学怪人answear

  
  @HostListener('click')
  clickInside($event) {
    this.text = "clicked inside";
    $event.stopPropagation();
  }
  
  @HostListener('document:click')
  clickout() {
      this.text = "clicked outside";
  }


-1

您可以调用事件函数,例如(focusout)或(blur),然后将您的代码

<div tabindex=0 (blur)="outsideClick()">raw data </div>
 

 outsideClick() {
  alert('put your condition here');
   }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.