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)...

问题:

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  {

}

回答1:

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;
    }
  }
  • 发表于 2019-03-07 17:59
  • 阅读 ( 190 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除