[英]How i can close/hide a modal popup if i click outside the modal popup
[英]How to close modal popup based on outside click using Angular8
我通過在其他組件中調用它的選擇器來調用一個組件,所以它顯示為彈出窗口,但我想在我做外部點擊時關閉它,任何人都可以幫助我如何做到這一點。
HTML 組件 1:
<div *ngIf="editAdditionalComment">
<app-comment></app-comment>
</div>
評論組件:
<div id="additionalCommentModal" class="dialog-container" keytestdirective (goListingPage)="keyDetails($event)" >
<div class="modal-dialog modal-dialog-centered" data-backdrop="static" role="document" >
<div class="modal-content" >
<div class="modal-header bg-info">
<h5 class="modal-title text-white">{{editModeData.modeHeader}}</h5>
<button type="button" class="close font-lg" data-dismiss="modal" aria-label="Close" (click)="cancelChanges()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Hello Hai</h6>
</div>
</div>
</div>
</div>
這是我使用的指令:
import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core';
@Directive({
selector: '[inigoClickOutside]'
})
export class ClickOutsideDirective {
//----------------------------------------------------------------------//
@Output("outsideClick")
public clickOutside = new EventEmitter<MouseEvent>();
//----------------------------------------------------------------------//
constructor(private _elementRef: ElementRef) {
}
//----------------------------------------------------------------------//
@HostListener('document:click', ['$event.path'])
public onGlobalClick(targetElementPath: Array<any>) {
const elementRefInPath = targetElementPath.find(e => e === this._elementRef.nativeElement);
if (!elementRefInPath) {
this.clickOutside.emit(null);
}
}
//----------------------------------------------------------------------//
}//Cls
用法:
<div inigoClickOutside (outsideClick)="onOutsideClick()"></div>
您可以創建一個識別點擊的背景 div,因此在您的代碼中將如下所示:
.div-background{ position: fixed; height: 100vh; width: 100vw; }
<div class="div-background" (click)="editAdditionalComment = false"> <div id="additionalCommentModal" class="dialog-container" keytestdirective (goListingPage)="keyDetails($event)" > <div class="modal-dialog modal-dialog-centered" data-backdrop="static" role="document" > <div class="modal-content" > <div class="modal-header bg-info"> <h5 class="modal-title text-white">{{editModeData.modeHeader}}</h5> <button type="button" class="close font-lg" data-dismiss="modal" aria-label="Close" (click)="cancelChanges()"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <h6>Hello Hai</h6> </div> </div> </div> </div> <div>
如果需要將事件返回給父組件,可以創建一個Output:
@Output() onClickBackground = new EventEmitter() this.onClickBackground.emit(true)
<div *ngIf="isShowingComment"> <app-comment (onClickBackground)="isShowingComment = false"></app-comment> </div>
這是演示: 演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.