2

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.