简体   繁体   中英

dismiss bootstrap alert in Angular 2+ by clicking outside of alert

I have the following alert in my Angular 2 web app:

HTML

<div class="alert alert-primary alert-dismissible fade show" role="alert" *ngIf="this.MiddleC == true">
    <strong>YES!!! That's Middle C!!!</strong>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
      </button>
  </div>

How do I write a TS method that closes this alert when I click anywhere else in the DOM? Not sure how to even go about this. Do I need to call this function from every other element in the DOM or is there a way around this?

One of the way to approach this problem would be creating additional "overlay" element, that would basically lay just below the modal in the DOM. Your html should look somewhere like:

<div class="overlay" (click)="this.MiddleC = false"></div>
<div class="alert alert-primary alert-dismissible fade show" role="alert" *ngIf="this.MiddleC == true">
  <strong>YES!!! That's Middle C!!!</strong>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

And then css:

.overlay{
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: MODAL_ZINDEX - 1;
}

Second way to approach it, could be @HostListener, this should work:

@HostListener('window:click', ['$event'])
onWindowClick($event){
  //check if its not modal that is clicked
}

https://angular.io/api/core/HostListener

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM