模態框是項目中經常會用到的一個公共功能,通常會被用左提示框或者擴展選項框。
下面,我用一個小例子來簡單展示實現模態框功能的過程:
1、為項目加包:
ng add ngx-bootstrap
2、在xxx.module.ts(模塊.ts文件)中引入:
... import { ModalModule } from "ngx-bootstrap/modal"; ... @NgModule({ imports: [ ... ModalModule.forRoot(), ... ] }) ...
3、創建一個模塊框公共組件:
//.ts部分 import { Component } from '@angular/core'; import { BsModalRef } from 'ngx-bootstrap'; @Component({ selector: 'response-modal', templateUrl: './response-modal.html' }) export class ResponseModalService { public header: string; public body: string; constructor(public modalRef: BsModalRef ) {} }
<!-- 模態框模板部分 .html --> <style> .centerize { text-align: center; } </style> <div class="container-fluid"><!-- 模態框容器樣式 --> <div class="modal-header"><!-- 框頭樣式 --> <h5>{{ header }}</h5> <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()"> <!-- 關閉按鈕樣式 --> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body" style="white-space: pre-line;"><!-- 框內容樣式 --> {{ body }} </div> <div class="centerize"> <button type="button" text-aling="center" class="btn btn-primary mr-2" (click)="modalRef.hide()">OK</button><!-- 常規按鈕樣式 --> </div> <p> </div>
4、在xxx.page.ts(模版.ts文件)中引入並,並調用:
import { BsModalRef, BsModalService } from "ngx-bootstrap";//引入模態框資源對象及服務對象
import {
ResponseModalService } from "src/app/shared/component/response-modal";
//引入上面創建好的模態框組件
... public modalRef: BsModalRef; ... constructor( private modalService: BsModalService, ... ) { ... } ... public openUpdateNotification(message: string): void { this.modalRef = this.modalService.show(ResponseModalService, {//初始化一個之前創建好的模態框組件 initialState: { header: "", body: message }, class: "modal-lg" }); }
5、在合適位置調用打開模態框的方法openUpdateNotification即可。