Search code examples
angularangular-materialangular-componentsmaterial-dialog

Using Component as dialog ref but not always


So I have a component which is sometimes used as a dialog ref and sometimes used normally outside of a dialog.

For example:

  • A form with a yes or no answer

Now sometimes I render this component inside a chat component (which is not a dialog) and sometimes I render this component by itself as a dialog.

Now, the issue is that I'm using:

  constructor(
    private dialogRef: MdDialogRef<PaymentFormComponent>
  ) {
  }

in the constructor as I want to be able to manually close the dialog when an event happens:

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

Now this is causing an issue when I'm using the component outside a dialog, because it saying this

ERROR Error: "No provider for MdDialogRef!"

Is it possible to only have this provided optionally and have it be null when it doesn't exist?


Solution

  • I think @Optional decorator will fix your issue

        @Optional()private dialogRef: MdDialogRef<PaymentFormComponent>
      ) {
      }