directive click outside angular 6

前端 未结 4 2170
广开言路
广开言路 2021-02-19 04:01

I upgraded my Angular from 4 to 6, and consequently had a problem with my click-off policy, it stopped working on all components.

my directive:



        
4条回答
  •  一生所求
    2021-02-19 04:13

    This is a modification of @YoungHyeong Ryu answer above, but with unsubscription, so that the handler stops working when the component is unmounted.

    DEMO https://stackblitz.com/edit/angular-1q4pga

    import { Component, Input, OnInit, OnDestroy, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'app-click-outside',
      template: `
    Click outside me.
    ` }) export class ClickOutsideComponent implements OnInit, OnDestroy { @ViewChild('insideElement', { static: false }) insideElement; public ngOnInit() { this.onDocumentClick = this.onDocumentClick.bind(this); document.addEventListener('click', this.onDocumentClick); } public ngOnDestroy() { document.removeEventListener('click', this.onDocumentClick); } protected onDocumentClick(event: MouseEvent) { if (this.insideElement.nativeElement.contains(event.target)) { return; } console.log('Clicked outside!'); } }

    Here, we remove the event listener on destroy. Also, normally a method added by addEventListener is executed in a global context (instead of this context); so we should take care of it and bind onDocumentClick method to this (we do it in ngOnInit). Now we can use this inside onDocumentClick.

提交回复
热议问题