NullInjectorError: No provider for MatDialogRef
I had this error when adding dialogs to a service to be shared in many components. Just to clarify, the error wasn't present in the application before moving dialogs to the service. The solution was to include a custom provider MatDialogRef
in the main module
import { DialogService } from './services/dialog.service';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';
...
imports: [
...
MatDialogModule
],
providers: [
{
provide: MatDialogRef,
useValue: {}
},
DialogService
],
...
With this provider the service worked as a singleton with my dialogs to be shared and the provider error was gone.
Thanks to the @Edric, i'v solved the problem by importing MatDialogModule
, MatDialog
and MatDialogRef
from @angular/material/dialog
instead of @angular/material
For example you are using app-checkout
It could be happen if you use a component in both 'dialog' and 'normal' way add app-checkout
in normal html file.
Solution 1:
remove <app-checkout> </app-checkout>
if you dont need import it in normal way in html file
Solution 2 using in both dialog and html file. Instead of this:
// ... something have selector: "app-checkout",
constructor(
public dialogRef: MatDialogRef<CheckoutComponent>,
@Inject(MAT_DIALOG_DATA) public dialogData: any
) {}
you need to inject it (to make it optional inject):
this way:
constructor(
// only need the @Optional() before the public dialogRef
@Optional() public dialogRef: MatDialogRef<CheckoutComponent>,
@Inject(MAT_DIALOG_DATA) public dialogData: any
) {
}
or this way:
// ... the same above
private dialogRef = null;
private dialogData;
constructor(private injector: Injector) {
this.dialogRef = this.injector.get(MatDialogRef, null);
this.dialogData = this.injector.get(MAT_DIALOG_DATA, null);
}
I had this Error and fixed it what you have to do is
-
check if you inserted import statement in the typescript file like this
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
-
check the constructor
constructor(@Optional() public dialogRef: MatDialogRef<GadgetAuthMessagesComponent>, @Inject(MAT_DIALOG_DATA) public message: string){ }
-
now go to module .ts and check the imports
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
-
in module.ts we need to put MatDialogModule name under imports array
MatDialogModule
-
now that's done finally we have to update the providers array
providers:
[{
provide: 'gadget-mlt',
useValue: GadgetMltComponent,
},
{provide:MatDialogRef , useValue:{} },
{ provide: MAT_DIALOG_DATA, useValue: {} }
],
Now It should work , Hope this Helps someone !