stackblitz.com/edit/base-d…css
點擊按鈕,出現彈窗,背後還有遮蓋層,彈窗的內容能夠自定義html
ng g c --name base-dialog
獲得三個初始化的文件base-dialog.component.html
<div class="modal-overlay" *ngIf="visible"></div>
複製代碼
對應的樣式 base-dialog.component.scss
bash
.overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1200;
background-color: rgba(0, 0, 0, 0.3);
touch-action: none; /* 不觸發任何事件 */
-ms-touch-action: none;
}
複製代碼
效果:遮蓋整個屏幕app
默認狀況下,遮蓋層是不顯示的動畫
@Input() dialogTitle = '';
/*
* 顯示/隱藏
* */
_visible = false;
constructor() { }
ngOnInit() {
}
show() {
this._visible = true;
}
close() {
this._visible = false;
}
複製代碼
<div class="overlay"></div>
<div class="dialog-container">
<div class="dialog-content">
<div class="dialog-header">{{dialogTitle}}</div>
<div class="dialog-body">
<ng-content select=".dialog-body"></ng-content>
</div>
<div class="dialog-footer">
<ng-content select=".dialog-footer"></ng-content>
</div>
</div>
</div>
複製代碼
補充樣式this
.overlay {
....
}
.dialog-container {
position: fixed;
z-index: 1300;
left: 50%;
top: 50%;
background-color: #fff;
.dialog-content {
border-radius: 8px;
padding: 10px;
}
.dialog-body {
}
.dialog-footer {
text-align: right;
}
}
複製代碼
這裏有一個細節是base-dialog
的z-index
必定要大於overlay
的,已保證dialog能顯示在遮蓋層上方。spa
app.component.html
, 加入下面的代碼<button (click)="dialogRef.show()">Show</button>
<app-my-dialog class="dialog-container" dialogTitle="這是標題" #dialogRef>
<ng-container class="dialog-body">
<div>
<p>這是內容</p>
</div>
</ng-container>
<ng-container class="dialog-footer">
<button (click)="dialogRef.close()">關閉</button>
</ng-container>
</app-my-dialog>
複製代碼
<ng-container class="dialog-body">
相似Vue中的插槽,以內的html會替換組件內部的<ng-content select=".dialog-body"></ng-content>
效果以下,點擊show按鈕,顯示彈窗,點擊彈窗中的關閉按鈕,恢復原樣。