Angular 實現一個 Dialog 組件

  1. 效果以下

stackblitz.com/edit/base-d…css

點擊按鈕,出現彈窗,背後還有遮蓋層,彈窗的內容能夠自定義html

  1. 打開一個全新的 Angular 項目,而後執行建立組件命令 ng g c --name base-dialog 獲得三個初始化的文件

image.png

  1. 首先製做遮蓋層,就是鋪滿整個屏幕的div base-dialog.component.html
<div class="modal-overlay" *ngIf="visible"></div>
複製代碼

對應的樣式 base-dialog.component.scssbash

.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

image.png

默認狀況下,遮蓋層是不顯示的動畫

@Input() dialogTitle = '';
  /*
  * 顯示/隱藏
  * */
  _visible = false;
  constructor() { }

  ngOnInit() {
  }

  show() {
    this._visible = true;
  }

  close() {
    this._visible = false;
  }
複製代碼
  1. 製做彈窗Dialog區域
<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-dialogz-index必定要大於overlay的,已保證dialog能顯示在遮蓋層上方。spa

  1. 打開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>
複製代碼
  • dialogRef 是這個組件的引用別名
  • <ng-container class="dialog-body"> 相似Vue中的插槽,以內的html會替換組件內部的<ng-content select=".dialog-body"></ng-content> 效果以下,點擊show按鈕,顯示彈窗,點擊彈窗中的關閉按鈕,恢復原樣。

image.png

  1. 其實大部分功能已經完成了,剩下的是樣式美化和添加一些額外功能,好比如今是居中顯示,示例中加入了從底部顯示,用到了CSS3中的動畫。
相關文章
相關標籤/搜索