Angular 6-如何隐藏该div外部的div onclick

时间:2019-06-23 17:46:33

标签: html angular typescript

我有一个按钮和一个div,当我单击按钮时,div用于切换。但是当我在该div之外单击时,我也需要隐藏div。这是下面的代码。

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 个答案:

答案 0 :(得分:2)

您可以使用HostListener来获取文档的点击事件。

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

请确保在$event.stopPropagation()函数中添加了clickit()

您还应该将div添加(click)="$event.stopPropagation()"

答案 1 :(得分:0)

在div上添加(click)="$event.stopPropagation()"以停止冒泡效果

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

使用 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;
    }
}

答案 2 :(得分:0)

波纹管将显示另一个div并将其置于全屏位置。他将对您不可见,但您仍然可以在整个页面上单击它。

<button (click)="click()">hide</button>
  <div *ngIf="show">Show</div>
  <div *ngIf="show" (click)='click()' style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: none"></div>