angular - 由于某种原因没有出现 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 { }
解决方案
请确保你有所有的最低限度。否则它不会工作:) 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();
}
...
}
推荐阅读
- javascript - 我可以在没有 Javascript 的情况下使这些卡片内的内容高度水平/相等吗?
- javascript - 在合并数组和数组反转中添加对象字段
- ruby-on-rails - 现有应用程序的 Rails shopify_app gem 更新
- javascript - JavaScript filter() 数组方法可以直接改变函数参数吗
- postgresql - 无法连接到 Helm 中的 PostgreSQL 作为 Minikube 中的依赖项
- mysql - 根据问题编写 SQL 语句
- android - Flutter:使用 minifyEnabled 的发布模式下的 Firestore 不可用错误
- javascript - 承诺后Vue重新加载单个元素
- php - Nginx 在子目录中访问 PHP(已解决)
- javascript - 使用纯 JavaScript(不是库)-> 如果 URL#1 在 5 秒内未加载,则打开 URL#2