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