打开对话框不起作用,材质角6

时间:2019-03-11 22:17:42

标签: angular dialog angular-material

我的“材质”对话框上的.open()在Angular 6中不起作用。我收到的错误是:

  

错误TypeError:无法读取未定义的属性“ open”

可能出什么问题了?似乎无法识别MatDialog的导入

父组件:

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() {
   ...
  }
}

对话框组件:

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();
  }

}

2 个答案:

答案 0 :(得分:0)

您需要将MatDialogModule添加到module.ts中的imports数组中,并将CourseDialogComponent添加到入口组件和声明数组中,例如:

import {MatDialogModule} from "@angular/material";
@NgModule({
declarations: [
 ...
 CourseDialogComponent
],
imports: [
 ...
 MatDialogModule
],
providers: [
 ...
],
bootstrap: [AppComponent],
entryComponents: [CourseDialogComponent]
})

export class AppModule {
}

答案 1 :(得分:0)

我们需要在App模块的2个位置导入Dialog组件

  1. 声明
  2. entryComponents

此后,无需在对话框组件中提供选择器,请参见以下示例。

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();
  }
}