这是一个简化ngx-bootstrap modal的基本用法的建议。
这个想法是使用2个指令:
bsDismissModal
data-dismiss="modal"
attribute [bsToggleModal]="modalTemplate"
data-toggle="modal"
and data-target="#exampleModal"
attributes ng-template
引用作为输入值用法示例:
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" [bsToggleModal]="exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<ng-template #exampleModal>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" bsDismissModal>×</button>
<h5 class="modal-title">Modal title</h5>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" bsDismissModal>Cancel</button>
<button type="button" class="btn btn-primary" (bsDismissModal)="save($event)">Save</button>
</div>
</div>
</div>
</div>
</ng-template>
答案 0 :(得分:1)
一种简单的方法是使用BsModalService
:
DismissModalDirective
import { Directive, EventEmitter, HostListener,
Inject, Output } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { BsModalService } from 'ngx-bootstrap/modal';
@Directive({
selector: '[dapDismissModal]'
})
export class DismissModalDirective {
// tslint:disable-next-line:no-output-rename
@Output('dapDismissModal') modalClosed = new EventEmitter<MouseEvent>();
private get modalsCount() {
return this.modalService.getModalsCount();
}
constructor(
private readonly modalService: BsModalService,
@Inject(DOCUMENT) private readonly document: Document
) {}
@HostListener('click', ['$event'])
hideModal(click: MouseEvent) {
this.modalClosed.emit(click);
if (click.defaultPrevented) {
return;
}
this.modalService.hide(this.modalsCount);
// Fix BsModalService
if (this.modalsCount === 0) {
this.document.body.classList.remove('modal-open');
}
}
}
(dismissModal)="handleClick($event)"
取代(click)="handleClick($event)"
,$event
为点击MouseEvent
。 event.preventDefault();
。ToggleModalDirective
import { Directive, HostListener, Input, TemplateRef } from '@angular/core';
import { BsModalService, ModalOptions } from 'ngx-bootstrap/modal';
@Directive({
selector: '[bsToggleModal]'
})
export class ToggleModalDirective {
// tslint:disable-next-line:no-input-rename
@Input('bsToggleModal') content: TemplateRef<any>;
@Input() bsModalConfig: ModalOptions;
constructor(private readonly modalService: BsModalService) {}
@HostListener('click')
showModal() {
this.modalService.show(this.content, this.bsModalConfig);
}
}