首页 > 解决方案 > 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();
  }

}

标签: angulardialogangular-material

解决方案


We need to import our Dialog component in 2 places of the App module

  1. declarations
  2. 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();
  }
}

推荐阅读