physicsboy
physicsboy

Reputation: 6316

Simple way to detect click outside of child component

I want to expand and contract child div component depending on the value of a variable, but I want to be able to click out of that component (in the parent of the sibling) as well as collapsing it.

Here's an stackblitz example. I have attempted to use HostListener from what I found in this question, but it did not help my case.

 @HostListener('document:click', ['$event'])
    documentClick(event: MouseEvent) {
        // your click logic
    }

Objectives:

  1. When I click on the child (hello) component, I want it to expand if it is not already and contract if it is already expanded
  2. When I click on anything else (ie. parent or sibling component), I want the child (hello) component to contract if it is expanded.

I do not want the child (hello) component to expand when clicking in the parent/sibling.

Update: Using HostListener

hello.component.html

<div class="box" (click)="clicked()" [ngClass]="{large: isEnlarged}">Hello.component</div>

hello.component.ts

export class HelloComponent  {
  isEnlarged = false;

  clicked() {
    this.isEnlarged = !this.isEnlarged;
  }

  @HostListener('document:click', ['$event'])
  documentClick(event: MouseEvent) {
    console.log('clicked');
    this.isEnlarged = false;
  }
}

app.component

export class AppComponent  {

}

Upvotes: 2

Views: 1656

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10127

The problem is your click handler is setting expanded to true before document click event handler sets it to false, so it's always false.

You could only set it to false if the event target is not your component:

https://stackblitz.com/edit/mouse-click-anywhere-8bwg6p?file=src/app/hello.component.ts

  @HostListener('document:click', ['$event'])
  documentClick(event: MouseEvent) {
    console.log('clicked');
    console.log(event);
    if (event.target.id !== 'box') {
      this.isEnlarged = false;
    }
  }

Upvotes: 2

Related Questions