Angular 6 - How can I hide a div onclick of outside of that div

Viewed 15059

I have a button and a div,When I click the button the div is used to toggle.But I need to hide the div also when I click outside of that div.Here the code below.

app.component.html

<button (click) ="clickit()">Click here</button>
<div style="border:1px solid;height:200px;width:200px;" *ngIf="show">Toggle hide and show</div>

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name: string = '2019-01-01T23-00-11';
  //name: string = '2019-01-01';
  show:any;
  ngOnInit() {

  }
clickit(){
this.show = !this.show;
}
}
3 Answers

You can use HostListener to get the click event of document.

@HostListener('document:click', ['$event']) onDocumentClick(event) {
  this.show = false;
}

Please make sure you added $event.stopPropagation() in your clickit() function.

You should add (click)="$event.stopPropagation()" to the div as well.

Add (click)="$event.stopPropagation()" on div for stop bubbling effect

<div style="border:1px solid;height:200px;width:200px;" *ngIf="show" (click)="$event.stopPropagation()" >Toggle hide and show</div>

Try this by using HostListener

 import { Component , HostListener} from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})

export class AppComponent {
  name: string = '2019-01-01T23-00-11';
  //name: string = '2019-01-01';
  show:any;

  @HostListener('document:click', ['$event'])

    clickout() {
     this.show = false;
    }




  ngOnInit() {

  }
    clickit(){
    this.show = !this.show;
    }
}

Try This HTML

<div class="d-flex p-2 links">
    <a (click)="showPopup(1,$event)"><img src="../../assets/icons/toolbar/settings.png" /></a>
  </div>
  <div class="user-mention" *ngIf="opened == true" (click)="$event.stopPropagation()">
      <div class="listing"> {{userEmail}}</div>
      <div class="listing" (click)="logout()">Logout</div>
  </div>

TS Code

@HostListener('document:click', ['$event']) onDocumentClick(event) {
    this.showPopup(2,event);
    event.stopPropagation()  
  }



opened: any = false;
  showPopup(id, event) {
    if(id == 1) {
      this.opened = true;
      event.stopPropagation()
    } else {
      this.opened = false;
    }
  }
Related