-1

There is this in constructor of component:

export class MyDialogComponent implements OnInit, OnDestroy {

 constructor(
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {}

}

What does it mean: @Inject(MAT_DIALOG_DATA)?

POV
  • 11,293
  • 34
  • 107
  • 201
  • 2
    Possible duplicate of [Angular 4: When and why is @Inject is used in constructor?](https://stackoverflow.com/questions/47050450/angular-4-when-and-why-is-inject-is-used-in-constructor) – Shifenis Sep 17 '19 at 15:28
  • Why not simple: constructor(public data: any)? – POV Sep 17 '19 at 15:30

2 Answers2

2

0) Definition of @Inject

The Angular Inject decorator definition taken from rangle.io:

@Inject()

@Inject() is a manual mechanism for letting Angular know that a parameter must be injected.

1) Definition of MAT_DIALOG_DATA

From the angular material dialog api:

MAT_DIALOG_DATA

Injection token that can be used to access the data that was passed in to a dialog.

2) Usage of @Inject(MAT_DIALOG_DATA) from the material documentation

In the dialog docs you can find how to share your data with a dialog component.

If you want to share data with your dialog, you can use the data option to pass information to the dialog component.

let dialogRef = dialog.open(YourDialog, {
  data: { name: 'austin' },
});

To access the data in your dialog component, you have to use the MAT_DIALOG_DATA injection token:

import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';

@Component({
  selector: 'your-dialog',
  template: 'passed in {{ data.name }}',
})
export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}

3) Full stackblitz example

Additional the material documentation provides a simple full working example at stackblitz.

zerocewl
  • 11,401
  • 6
  • 27
  • 53
0

Within such a factory function, using this function to request injection of a dependency is faster and more type-safe than providing an additional array of dependencies (as has been common with useFactory providers).

Dependency Injection (DI) recapitulation If you use Inject then you don't need to pass service in providers: []

Suhag Lapani
  • 655
  • 10
  • 18