I do this, but on the mobile iPhone it does not work. Works everywhere except iPhone
@HostListener('document:click', ['$event.target'])
public onClick(targetElement: HTMLElement): void {
if (!targetElement) {
return;
}
const clickedInside = this._elementRef.nativeElement.contains(
targetElement
);
if (!clickedInside && targetElement.className.indexOf('title') === -1) {
console.log('click outside');
}
After some research, this should work
@HostListener('document:touchend', ['$event'])
@HostListener('document:click', ['$event'])
onClick(event: MouseEvent): void {
if (this.container.nativeElement.contains(event.target)) {
// this is inside
} else {
// this is outside
}
}
this way works on iPhone 5, the difference is using container variable which is ViewChild ref to the wrapped element in your component
TS:
@ViewChild('container') container;
@HostListener('document:click', ['$event'])
outClickHandler(event: Event): void {
if (!this.container.nativeElement.contains(event.target)) {
console.log('click outside');
}
}
and HTML
<div #container>
...content
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.