添加指令以简化ngx-bootstrap模式

时间:2017-11-27 12:51:27

标签: ngx-bootstrap

  

这是一个简化ngx-bootstrap modal的基本用法的建议。

这个想法是使用2个指令:

用法示例:

<!-- 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>

1 个答案:

答案 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);
    }
}