Problem Statment
I am learning Angular 4 and I have stumble upon a code where @Inject
is being used in a constructor
and I am not able to figure out why...
Code and Source
I am using Angular 4 Material
Code Source: https://material.angular.io/components/dialog/overview
In the code, they are injecting MAT_DIALOG_DATA
constructor(public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: any
) { }
Can anyone please elaborate what does it mean and when/where should we do this?
@Inject()
is a manual mechanism for letting Angular know that a parameter must be injected.import { Component, Inject } from '@angular/core'; import { ChatWidget } from '../components/chat-widget'; @Component({ selector: 'app-root', template: `Encryption: {{ encryption }}` }) export class AppComponent { encryption = this.chatWidget.chatSocket.encryption; constructor(@Inject(ChatWidget) private chatWidget) { } }
In the above we've asked for
chatWidget
to be the singleton Angular associates with theclass
symbolChatWidget
by calling@Inject(ChatWidget)
. It's important to note that we're usingChatWidget
for its typings and as a reference to its singleton. We are not usingChatWidget
to instantiate anything, Angular does that for us behind the scenes
From https://angular-2-training-book.rangle.io/handout/di/angular2/inject_and_injectable.html