我正在使用angular 6和ngx-bootstrap 3.0.1
我显示一个模式,当用户在更新表单后尝试关闭该模式时,我希望能够显示“放弃/取消”确认。
当用户使用我的自定义关闭按钮时,我没有问题,但是当他在模式外部使用背景单击时,我不知道如何调用我的关闭函数。
我如何整洁地处理背景单击以显示我的确认消息?
谢谢
答案 0 :(得分:1)
在ngx-bootstrap文档页面中,您可以轻松找到解决方案:https://valor-software.com/ngx-bootstrap/#/modals#directive-events
要查看正在触发什么事件,
在组件方面,
import { Component, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
@Component({
selector: 'demo-modal-events',
templateUrl: './events.html',
styles: [`
.card {
margin-bottom: 0.75rem;
padding: 8px;
}
`]
})
export class DemoModalEventsComponent {
@ViewChild(ModalDirective) modal: ModalDirective;
messages: string[];
showModal() {
this.messages = [];
this.modal.show();
}
handler(type: string, $event: ModalDirective) {
this.messages.push(
`event ${type} is fired${$event.dismissReason
? ', dismissed by ' + $event.dismissReason
: ''}`
);
}
}
在模板方面,
<button type="button" class="btn btn-primary" (click)="showModal()">Open a modal</button>
<br><br>
<pre class="card card-block card-header" *ngFor="let message of messages">{{message}}</pre>
<div class="modal fade" bsModal #modal="bs-modal"
tabindex="-1" role="dialog" aria-labelledby="dialog-events-name"
(onShow)="handler('onShow', $event)"
(onShown)="handler('onShown', $event)"
(onHide)="handler('onHide', $event)"
(onHidden)="handler('onHidden', $event)">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 id="dialog-events-name" class="modal-title pull-left">Modal</h4>
<button type="button" class="close pull-right" aria-label="Close" (click)="modal.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Just another modal <br>
Click <b>×</b>, press <code>Esc</code> or click on backdrop to close modal.
</div>
</div>
</div>
</div>
更新:
据我了解,您可以像这样检查$ event:
if($event.dismissReason == 'backdrop-click')
this.myFunc();
答案 1 :(得分:1)
使用选项打开模态
this.bsModalRef = this.modalService.show(ExampleModal, {
ignoreBackdropClick: true,
keyboard: false
});
在ExampleModal中放置此代码
ngOnInit(): void {
document.documentElement.addEventListener('click', this.hideIfIsBackdropClick.bind(this));
}
hideIfIsBackdropClick(event: any): void {
if (event.target.classList.contains('modal')) {
this.hide();
}
}
hide(): void {
if (anyBooleanHere) {
this.bsModalRef.hide();
}
}
答案 2 :(得分:0)
您可以使用钩子ngOnDestroy()
来检测用户何时关闭模态