首页 > 解决方案 > 由于某种原因没有出现 Angular 对话框窗口

问题描述

我需要为我的项目实现一个对话窗口,但由于某种原因我无法让它工作。对话窗口不会打开,但对话组件的内容会像 HTML 元素一样添加到页面的末尾,而不会使页面的其余部分变暗。这不像我在做任何复杂的事情。我现在只是想打开一个简单的对话窗口。我写的东西与 Youtube 上的人或官方文件并没有什么不同。我多次检查代码但找不到错误。我错过了什么吗?

对话框组件:

import { Component, OnInit } from '@angular/core';

@Component({
     selector: 'app-dialog',
     templateUrl: './dialog.component.html',
     styleUrls: ['./dialog.component.scss']
})
export class DialogComponent implements OnInit {

     constructor() { }


     ngOnInit() {
     }

}

对话框 HTML:

<p>
     dialog works!
</p>

主页面组件:

import { Component } from '@angular/core';
import { MatDialog } from '@angular/material';
import { DialogComponent } from './Components/dialog/dialog.component';

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
})
export class AppComponent {

     constructor(public dialog: MatDialog) {
          this.openDialog();
     }

     openDialog() {
          const dialogRef = this.dialog.open(DialogComponent, {
               width: '500px',
               height: '1080px'
          });

          dialogRef.afterClosed().subscribe(result => {
               console.log(`Dialog result: ${result}`);
          });
     }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { DialogComponent } from './Components/dialog/dialog.component';
import { MatDialogModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
     declarations: [
          AppComponent,
          DialogComponent,
     ],
     imports: [
          BrowserModule,
          AppRoutingModule,
          FormsModule,
          MatDialogModule,
          BrowserAnimationsModule,
     ],
     providers: [],
     bootstrap: [AppComponent],
     entryComponents: [
          DialogComponent
     ],
})
export class AppModule { }

标签: angulartypescript

解决方案


请确保你有所有的最低限度。否则它不会工作:) http://material.angular.io/guide/getting-started

您在对话框的构造函数中缺少 MatDialogRef

import { MatDialogRef } from '@angular/material';

constructor(public dialogRef: MatDialogRef<DialogComponent>) {
}

主页面组件

像这样调用是不可能的(那时 UI 还没有准备好):

constructor(public dialog: MatDialog) {
      this.openDialog();
 }

它应该是(或 afterviewinit)

import { OnInit } from '@angular/core';

export class AppComponent implements OnInit {

    ...

    ngOnInit() {
       this.openDialog();
    }

    ...
}

推荐阅读