DEV Community

danielpdev
danielpdev

Posted on

2 2

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (2)

Collapse
 
alleamitrano profile image
~AlleAmiDev~

Hi Daniel! I don't understand. Why would you want to inject services this way when they can be provided in Root and initialised in the constructor?

Collapse
 
danielpdev profile image
danielpdev

@Hi AlleAmiDev sorry, but maybe I wasn't enough clear about it.

You are right, using @Inject() it's not a desired way to inject services into your components, but that was just an example.

You should use @Inject('value') when you need to inject just a specific value and not a whole instance.

For ex:

providers: [
    {
      provide: "language",
      useValue: "en"
    }
  ],

and then in your components:

...
    @Inject("language") private language,
....

Did I answer your question? :-)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay