Angular2+之模态框-使用ngx-bootstrap包中的模态框组件实现

模态框是项目中经常会用到的一个公共功能,通常会被用左提示框或者扩展选项框。

下面,我用一个小例子来简单展示实现模态框功能的过程:

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文件)中引入并,并调用:

扫描二维码关注公众号,回复: 7485631 查看本文章
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即可。

猜你喜欢

转载自www.cnblogs.com/dyhblog/p/11691265.html