Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material: No provider for dialogRef

hey I'm trying to use angular material dialog and I face an issue:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[MatDialogClose -> MatDialogRef]: StaticInjectorError(Platform: core)[MatDialogClose -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!

module.ts:

...
import {
  MatDialogModule,
  MatInputModule,
  MatCardModule,
  MatButtonModule,
  MatToolbarModule,
  MatExpansionModule
} from "@angular/material";

...

@NgModule({
  declarations: [
    AppComponent,
    PostCreateComponent,
    HeaderComponent,
    PostListComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatInputModule,
    MatCardModule,
    MatButtonModule,
    MatToolbarModule,
    MatExpansionModule,
    MatDialogModule,
    HttpClientModule
  ],
  entryComponents: [PostCreateComponent],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

component1:

import { MatDialog } from "@angular/material";
 constructor(public dataService: DataService, public dialog: MatDialog) {}

    onEdit(postId: string) {
        this.dataService.editMode = true;
        this.dataService.postIdForEdit = postId;
        const dialogRef = this.dialog.open(PostCreateComponent, {
          width: "500px"
        });
      }

component2:

 import { MatDialogRef } from "@angular/material";


      constructor(
        private fb: FormBuilder,
        public dataService: DataService,
        public route: ActivatedRoute,
        private dialogRef: MatDialogRef<PostCreateComponent>
      ) {}

      ...


      onAddPost(form, formDirective: FormGroupDirective) {
   ...
           this.close();
        }

       close() {
 this.dialogRef.close();
      }
    }

I imported everything needed so why I get this error? where else I need to add the MatDialogRef instance? I have searched all over the net but found no answer to this problem .... thanks by heart

like image 866
hindi1991 Avatar asked May 18 '26 21:05

hindi1991


1 Answers

You need to import MatDialogModule, MatDialog and MatDialogRef from @angular/material/dialog instead of @angular/material

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

Also you need to make sure that MatDialogRef exists in providers array

providers: [{
  provide: MatDialogRef,
  useValue: {
    close: (dialogResult: any) => { }
  }
}]

Github issue

like image 84
Sajeetharan Avatar answered May 22 '26 10:05

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!