首先下载ngx-bootstrap
npm install ngx-bootstrap --save
然后如果需要加载 bootstrap 样式,还需要下载 bootstrap
npm install bootstrap --save
在scss里引入
@import url('bootstrap/dist/css/bootstrap.min.css')
下载后,在module.ts中导入ngx-bootstrap/modal
import { ModalModule } from 'ngx-bootstrap/modal';
imports: [ModalModule.forRoot()]
app.component.ts
import { Component, TemplateRef } from '@angular/core';
import { ChildComponent } from './components/child/child.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
bsModalRef: BsModalRef;
constructor(private modalService: BsModalService) { }
showModal() {
const initialState = {
title: '模态框'
};
// 显示弹框
this.bsModalRef = this.modalService.show(ChildComponent, { initialState });
// 子组件关闭后,触发的订阅函数
this.modalService.onHidden.subscribe(() => {
console.log('title', this.bsModalRef.content.title);
});
this.bsModalRef.content.onClose = (msg: string) => {
console.log('msg', msg);
this.bsModalRef.hide();
}
}
}
app.component.html
<button class="btn btn-primary btn-lg" (click)="showModal()">
演示模态框
</button>
child.component.ts
import { Component } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-child',
templateUrl: './child.component.html'
})
export class ChildComponent {
title: string = '';
onClose: any;
constructor(public bsModalRef: BsModalRef) { }
close() {
// 关闭弹窗
this.bsModalRef.hide();
}
close2() {
this.onClose('close');
}
}
child.component.html
<div class="modal-dialog modal-primary" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">{{title}}</h4>
<button type="button" class="close" (click)="close()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-secondary" (click)="close()">取消</button>
<button type="button" class="btn btn-outline-primary" (click)="close2()">确定</button>
</div>
</div>
</div>
效果: