Valentin Garcia
Valentin Garcia

Reputation: 495

use component without MatDialog, MatDialogRef<SomeComponent>

I have a function that opens a MatDialog with a component called 'NoteFormComponent' it looks like this

  openForm() {
    let dialogConfig = new MatDialogConfig();
    dialogConfig.autoFocus = true;
    dialogConfig.width = "95%";
    dialogConfig.panelClass = "form-dialog";
    dialogConfig.scrollStrategy = new NoopScrollStrategy();

    this.dialog.open(NoteFormComponent, dialogConfig).beforeClose().subscribe(() => this.getNotes());
  }

I pops up a modal containing the 'NoteFormComponent'. So WHAT is the problem?

The problem is that I want to use 'NoteFormComponent' without a MatDialog, but in order to use it with the MatDialog I had to inject a reference in the component's constructor like this

  constructor(
    private noteService : NoteService, 
    private productService : ProductService,
    private categoryService : CategoryService,
    private clientService : ClientService,
    private notification : NotificationService,
    private dialogRef : MatDialogRef<NoteFormComponent>, /*This Reference*/
    private loader : LoaderService,
    private sessionService : SessionService,
    private securityBlockerService : SecurityBlockerService,
    private dialog : MatDialog,
    private dialogService : DialogService
  ) { }

And if I try to use the component with the template selector '' it throws an error that there is no provider for MatDialogRef, the only thing that comes to my mind is create a copy of the 'NoteFormComponent' but without the MatDialogRef injector in the constructor.

Is there anyway to solve or work around this problem?

Upvotes: 4

Views: 2604

Answers (1)

Eiman
Eiman

Reputation: 761

Use the @Optional() decorator when injecting the MatDialogRef in constructor (Reference):

constructor(
    ...
    @Optional() private dialogRef: MatDialogRef<NoteFormComponent>,
    ...
) { ... }

By doing this, you can consume the NoteFormComponent in the normal way, without using MatDialog.

Upvotes: 12

Related Questions