panay
panay

Reputation: 90

Angular. How to define a click outside, excluding sub-components?

everyone!

There is a code for determining the click outside the component

@HostListener('document:click', ['$event', '$event.target'])
public onClick($event, targetElement) {
    const isClickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!isClickedInside) {
        this.onClickOutsideEvent.emit($event);
    }
}

Why is the click defined outside, if clicked inside, but on the nested component?

Upvotes: 2

Views: 1614

Answers (1)

Vega
Vega

Reputation: 28708

The logic of the above code works when you set it as a listener on a wrapper div of the element you wish to monitor. That div should be screen size and will receive all the click events on the document. And when the click is not inside that div, then it's inside the element you are monitoring, by elimination logic. I would complete it to the following:

    @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);
        }
    }

demo

Upvotes: 1

Related Questions