Provide simple value for components in Angular

danielpdev

danielpdev

Posted on March 16, 2020

Provide simple value for components in Angular

Sometimes you need to inject a simple value into multiple components

Edit provide-use-value

To inject a simple value you have to pass an object to the providers array of your NgModule decorator.

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    {
      provide: "language",
      useValue: "en"
    }
  ],
  bootstrap: [AppComponent]
})

And in your components import Inject decorator:
@Inject() is a decorator relevant for DI and helps you manually inject a value into your components.

import { Component, Inject } from "@angular/core";

....
export class AppComponent {
  constructor(@Inject("language") private language) {
    console.log(this.language);
  }
}

You can also use @Inject() decorator to provide services from your module.

Ex:

import { Component, Inject } from "@angular/core";
import { AppService } from "./app.service";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  constructor(
    @Inject("language") private language,
    @Inject(AppService) private appSer,
    private appSer2: AppService
  ) {
    console.log(this.language, this.appSer, this.appSer2);
  }
}

Using:

...
    @Inject(AppService) private appSer,
    private appSer2: AppService
...

Above code illustrates 2 ways of injecting a service into your component.

Hope you find it useful and see you on the next post!
Stay safe!

💖 💪 🙅 🚩
danielpdev
danielpdev

Posted on March 16, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related