我需要为我的项目实现一个对话窗口,但由于某种原因我不能让它工作。对话框窗口不会打开,但对话框组件的内容会像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 { }
请确保您已准备好所有最小的。否则它将无法正常工作:) 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();
}
...
}