我已经使用 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;
 }
}

这里的截图:
javascript - 将 Angular MatDialog居中-LMLPHP

最佳答案

此代码在要打开对话框的任何组件中。您必须具有对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);
MessageComponent
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的默认设置!

09-18 16:19