我用angular MatDialog實現了一個模態對話框,用來代替alert()函數。 除了對話框的位置,一切都很好。我無法將對話框放在頁面的中央。對話框總是出現在頁面的左下邊緣。
html文件如下所示:
<h2>Oups! Something went wrong.</h2>
<p>{{error}}</p>
<button class="btn-outline-primary" mat-dialog-close>OK</button>
這是打開對話框的函數
private openDialog(error: string) {
const dialogConfig = new MatDialogConfig();
dialogConfig.data = {
error: 'This is a test'
}
dialogConfig.disableClose = false;
dialogConfig.hasBackdrop = false;
dialogConfig.autoFocus = false;
dialogConfig.width = '600px';
dialogConfig.height = '200px';
this.dialog.open(ErrorDialogComponent, dialogConfig);
}
和組件類:
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from "@angular/material";
@Component({
selector: 'app-error-dialog',
templateUrl: './error-dialog.component.html',
styleUrls: ['./error-dialog.component.scss']
})
export class ErrorDialogComponent {
error: string;
constructor(@Inject(MAT_DIALOG_DATA) data) {
this.error = data.error;
}
}
以下是截圖:
# # #這段代碼在任何你想打開對話框的組件中。你必須引用MatDialog。mdRef是打開后對象的實例。
// getConfig returns a matDialogConfig with the data
mc = this.getConfig(data);
// Tell Matdialog which Angular component to use.
mdRef = this.md.open(MessageComponent, mc);
消息組件
import { MAT_DIALOG_DATA } from "@angular/material/dialog";
import { Component, OnInit, AfterViewInit, Inject } from "@angular/core";
import { inject } from "@angular/core/testing";
@Component({
selector: "lib-message",
templateUrl: "./message.component.html",
styleUrls: ["./message.component.css"],
})
export class MessageComponent implements OnInit, AfterViewInit {
constructor(@Inject(MAT_DIALOG_DATA) public data: any) {
// get the injected dialog data
this.data = data;
}
ngOnInit(): void {}
ngAfterViewInit() {}
}
還有css
:host {
display: grid;
justify-content: center;
align-items: center;
background-color: yellow;
position: absolute;
top: 10em;
left: 20em;
height: 10em;
width: 20em;
box-shadow: 0 0 5px rgb(0, 0, 0, 0.27);
}
摘要:消息組件的css覆蓋了cdkOverlay的默認設置!
上一篇python 裝飾器實現
下一篇vue多個li循環