import { Component } from '@angular/core';
@Component({
selector: 'app-nz-modal',
template: `
<div class="modal" [ngClass]="{ 'show': visible }">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">模态框标题</h5>
<button type="button" class="close" (click)="hide()">
<span>×</span>
</button>
</div>
<div class="modal-body">
模态框内容
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" (click)="hide()">关闭</button>
<button type="button" class="btn btn-primary">保存</button>
</div>
</div>
</div>
</div>
`,
styles: [
`
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0, 0, 0, 0.4);
}
.modal.show {
display: block;
}
.modal-dialog {
position: relative;
margin: auto;
max-width: 600px;
min-height: 200px;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h5 {
margin: 0;
}
.modal-header button {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
}
.modal-body {
margin-top: 20px;
margin-bottom: 20px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
}
.modal-footer button {
margin-left: 10px;
}
`
]
})
export class NzModalComponent {
visible = false;
show() {
this.visible = true;
}
hide() {
this.visible = false;
}
}
在子组件中,我们使用visible
属性控制模态框的显示与隐藏。在show()
方法中,将visible
属性设置为true
,在hide()
方法中,将visible
属性设置为false
。在模板中,我们使用[ngClass]
指令根据visible
属性的值动态添加show
类来控制模态框的显示与隐藏。
父组件调用
import { Component } from '@angular/core';
import { NzModalComponent } from './nz-modal/nz-modal.component';
@Component({
selector: 'app-parent',
template: `
<button (click)="showModal()">打开模态框</button>
<app-nz-modal #modal></app-nz-modal>
`
})
export class ParentComponent {
constructor(private modal: NzModalComponent) {}
showModal() {
this.modal.show();
}
}
在模板中,我们通过<app-nz-modal>
标签引入了子组件,并使用#modal
定义了一个模板引用变量。在组件中,我们通过constructor
注入了子组件,并在showModal()
方法中调用了子组件的show()
方法。