angular - Open Dialog not working, Material Angular 6
问题描述
My .open() on my Material Dialog is not working in Angular 6. The error I receive is:
ERROR TypeError: Cannot read property 'open' of undefined
What might be going wrong? It seems as if the import of MatDialog is not being recognized
Parent Component:
import { Component, OnInit, Input, Inject } from '@angular/core';
import { AuthService } from "../../services/auth.service";
import { SiteService } from "../../services/site.service";
import { MonitoringPointService } from "../../services/monitoring-point.service";
import { Router, ActivatedRoute } from '@angular/router';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { DialogComponent } from '../dialog/dialog.component';
@Component({
selector: 'app-site-settings',
templateUrl: './site-settings.component.html',
styleUrls: ['./site-settings.component.css']})
export class SiteSettingsComponent implements OnInit {
constructor(public dialog: MatDialog, private router: Router, private route: ActivatedRoute, public authService: AuthService, public siteService: SiteService,public monitoringPointService: MonitoringPointService ) { }
openDialog(): void {
const dialogRef = this.dialog.open(DialogComponent, {
width: '250px',
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
ngOnInit() {
...
}
}
Dialog Component:
import { Component, OnInit, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { SiteSettingsComponent } from '../site-settings/site-settings.component';
@Component({
selector: 'app-dialog',
templateUrl: './dialog.component.html',
styleUrls: ['./dialog.component.css']
})
export class DialogComponent implements OnInit {
constructor( public dialogRef: MatDialogRef<DialogComponent>) { }
ngOnInit() {}
onNoClick(): void {
this.dialogRef.close();
}
}
解决方案
We need to import our Dialog component in 2 places of the App module
- declarations
- entryComponents
After that no need to give selector in the Dialog Component, see the below example.
import { Component, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
@Component({
templateUrl: 'dialog.template.html',
})
export class DialogComponent {
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {}
onNoClick(): void {
this.dialogRef.close();
}
}
推荐阅读
- java - 表格、网格的设计模式
- wordpress - 没有存储 Wordpress 元框值
- azure - 使用 ASP.NET Core 网站在 Azure 上选择 .NET 或 .NET Core
- javascript - 如何从http响应中获取特定的json数据
- google-cloud-platform - 无法将存储库从 Google Cloud Source Repository 克隆到配置了 Cloud NAT 的 Compute Engine 实例
- c# - Byte[] 到浮点数的转换
- mysql - 从 MySQL Window 函数中的第一行、最后一行和聚合中获取值
- php - Laravel 未定义的变量,即使在设置 isset 之后
- java - 我在哪里可以找到 DL4J - INDArray 相关操作的已安装头文件?
- python - app.activateWithOptions() 和 app.activateWithOptions_() 之间的区别