Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular NullInjectorError: No Provider for MatDialog

so when I try to load my angular app, i get this error:

ERROR Error: Uncaught (in promise): 
NullInjectorError: StaticInjectorError(AppModule)[AppComponent -> MatDialog]:    
StaticInjectorError(Platform: core)[AppComponent -> MatDialog]:

my ts file looks like this, every other help question said to add MatDialog to my NgModule imports, but I have done that and am still receiving the error. Most of those errors were StaticInjectorErrors and mine is a NullInjectorError but I am not sure what the difference is between those two.

import { Component, NgModule } from '@angular/core';
import { MatDialog, MatDialogConfig, MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { compileNgModule } from '@angular/compiler';
import { AppDialog } from '../appDialog/app-dialog.component';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html'
})
@NgModule({
  imports: [MatDialog, MatDialogRef, MatDialogConfig, MatDialogModule]
})
export class AppComponent {


  constructor(private appService: AppService, private dialog: MatDialog) {
  }

  openDialog() {

    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = true;
    dialogConfig.height = "350px";
    dialogConfig.width = "600px";
    dialogConfig.data = {
    };

    const dialogRef = this.dialog.open(AppDialog, dialogConfig);
    dialogRef.afterClosed().subscribe(result => {
      console.log('closed dialog');
      this.success = result;
    })
  }
}
like image 290
Brandon Miller Avatar asked Jan 22 '20 01:01

Brandon Miller


2 Answers

In my situation, I was seeing this error while trying to build a dialog component like:

my-dialog.component.ts

<mat-dialog-container>
  <mat-dialog-content>
    <p>Hello</p>
    <p>I am a dialog</p>
  </mat-dialog-content>
  <mat-dialog-actions>
    <button mat-raised-button>Click me</button>
  </mat-dialog-actions>
</mat-dialog-container>

The problem was that I was using mat-dialog-container. This is not required for components that you'll be rendering via matDialog.open(MyDialogComponent)

Instead, just remove mat-dialog-container entirely and just use the child nodes.

like image 175
Brad Johnson Avatar answered Sep 27 '22 21:09

Brad Johnson


Please note that in Angular Material you have to import all elements module into your module.ts. You have to import and add module in your module.ts like this

import {MatDialogModule} from '@angular/material/dialog';


import : [MatDialogModule]

For reference see the example from official documentation here

like image 42
Fahad Hassan Avatar answered Sep 27 '22 20:09

Fahad Hassan