@HostListener OnClick for outside click does not work in firefox

后端 未结 2 1200
太阳男子
太阳男子 2021-01-13 07:16

@HostListener OnClick does not work in firefox. I tried onClick, onclick and onGlobalClick. They all work in chrome but no one in firefox. Here is my code:

c         


        
相关标签:
2条回答
  • 2021-01-13 07:45

    event.path returns undefined only in Firefox, but it returns an array in Chrome and Edge browser (ng-version="10.1.6").

    Solution - use event.composedPath() instead of event.path, its returns same array in Firefox, Chrome and Edge browser.

    HTML -

    <button (click)="onClick($event)">Demo Button</button>
    

    .ts -

    @HostListener('document:click', ['$event'])
    onClick(event: MouseEvent): void {
        console.log('event------', event.composedPath()); // working in Firefox, Chrome and Edge
    }
    
    0 讨论(0)
  • 2021-01-13 08:07

    Here is what I tested in all browsers and it works:

     @HostListener('document:click', ['$event', '$event.target'])
        onClick(event: MouseEvent, targetElement: HTMLElement): void {
            if (!targetElement) {
                return;
            }
            const clickedInside = this.elementRef.nativeElement.contains(targetElement);
            if (!clickedInside) {
                this.clickOutside.emit(event);
            }
        }
    
    0 讨论(0)
提交回复
热议问题