Brandon Miller
Brandon Miller

Reputation: 357

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

Upvotes: 17

Views: 21486

Answers (2)

Brad Johnson
Brad Johnson

Reputation: 1924

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.

Upvotes: 38

Fahad Hassan
Fahad Hassan

Reputation: 811

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

Upvotes: 18

Related Questions