gpt4 book ai didi

由于某种原因没有出现 Angular 对话窗口

转载 作者:行者123 更新时间:2023-12-04 15:46:14 24 4
gpt4 key购买 nike

我需要为我的项目实现一个对话窗口,但由于某种原因我无法让它工作。对话框窗口不会打开,但对话框组件的内容会像 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}`);
});
}
}

应用程序模块.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();
}

...
}

关于由于某种原因没有出现 Angular 对话窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com