angulardependency-injectionmat-dialog

angular dependency injection - ignore when not provided - use case: MAT_DIALOG_DATA


some of my components. have 2 way initial parameters via constructor.

  1. routes parameters, for using via url.
  2. matDialogData, used when comopnent opens in a dialog.

like this:

constructor(private dialog: MatDialog,
private route:ActivatedRoute,
@Inject(MAT_DIALOG_DATA) private data)

the option of matDialog work fine, but route option (was work fine before adding of matDialogData) fail with:

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[InjectionToken MatDialogData -> InjectionToken MatDialogData -> InjectionToken MatDialogData]: 
  NullInjectorError: No provider for InjectionToken MatDialogData!
NullInjectorError: R3InjectorError(AppModule)[InjectionToken MatDialogData -> InjectionToken MatDialogData -> InjectionToken MatDialogData]: 
  NullInjectorError: No provider for InjectionToken MatDialogData!

is there a way to config this parameter @Inject(MAT_DIALOG_DATA) private data as nullable/optional, and ignore from this error ?


Solution

  • you can use the @Optional() decorator like this:

    class SomeClass {
      constructor(
        private dialog: MatDialog,
        private route:ActivatedRoute,
        @Optional() @Inject(MAT_DIALOG_DATA) private data
      ) {}
    }