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:
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
.