Angular Material Dialog报错:this._portalOutlet is undefined 求助
问题描述
注:此问题并非Stack Overflow问题59054094的重复,该问题的解决方案对我无效。
我按照Angular Material官方文档使用MatDialog:
export class AppComponent implements OnInit{ constructor(public dialog: MatDialog) {} ngOnInit(): void { this.dialog.open(DialogAnimationsExampleDialog, { width: '250px', }) } }
我使用文档中的DialogAnimationsExampleDialog组件:
@Component({ selector: 'dialog-animations-example-dialog', template: `<h1 mat-dialog-title>Delete file</h1> <div mat-dialog-content> Would you like to delete cat.jpeg? </div> <div mat-dialog-actions> <button mat-button mat-dialog-close>No</button> <button mat-button mat-dialog-close cdkFocusInitial>Ok</button> </div>` }) export class DialogAnimationsExampleDialog { constructor(public dialogRef: MatDialogRef<DialogAnimationsExampleDialog>) {} }
代码编译成功,但浏览器控制台出现如下错误:
ERROR TypeError: this._portalOutlet is undefined
Angular 3
ngOnInit app.component.ts:15
模块定义
我尝试了以下几种模块配置,均出现相同错误
1. 初始配置
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent, DialogAnimationsExampleDialog} from './app.component'; import {MAT_DIALOG_DATA, MatDialog, MatDialogContainer, MatDialogModule} from "@angular/material/dialog"; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; @NgModule({ declarations: [ AppComponent, DialogAnimationsExampleDialog ], imports: [ BrowserModule, MatDialogModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent], }) export class AppModule { }
2. 参考Stack Overflow问题59054094后的配置
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent, DialogAnimationsExampleDialog} from './app.component'; import {MAT_DIALOG_DATA, MatDialog, MatDialogContainer, MatDialogModule} from "@angular/material/dialog"; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; @NgModule({ declarations: [ AppComponent, DialogAnimationsExampleDialog ], imports: [ BrowserModule, MatDialogModule, BrowserAnimationsModule ], providers: [ MatDialog, { provide: MAT_DIALOG_DATA, useValue: {} } ], bootstrap: [AppComponent], entryComponents: [MatDialogContainer] }) export class AppModule { }
修改调用时机
根据建议,错误可能与组件初始化不完整有关,因此我将this.dialog.open()调用放到按钮点击触发的方法中:
// app.component.ts openDialog() { this.dialog.open(DialogAnimationsExampleDialog, { width: '250px', }) }
<!--app.component.html--> <button (click)="openDialog()"> open </button>
但除了调用栈变化外,错误依然存在。
内容的提问来源于stack exchange,提问作者mapawa
相关产品推荐
相关产品推荐

