Blog>
Snippets

Using Injection Token in a Component

Provide an example of how to inject a value using an InjectionToken into an Angular component.
import { Injectable, InjectionToken, NgModule } from '@angular/core';

// Define an InjectionToken
export const APP_CONFIG = new InjectionToken('app.config');
This code creates a new InjectionToken named 'APP_CONFIG' which will be used to inject a configuration object into Angular components.
const AppConfig = { 
  apiUrl: 'https://api.example.com',
  otherConfig: 'value' 
};
This code defines the config object that we want to inject using the 'APP_CONFIG' InjectionToken.
@NgModule({
  providers: [
    { provide: APP_CONFIG, useValue: AppConfig }
  ]
  // ... (other module metadata)
})
export class AppModule { }
This code adds the config object to the module's providers array, using the InjectionToken 'APP_CONFIG' as the key and the predefined config object as the value.
import { Component, Inject } from '@angular/core';
import { APP_CONFIG } from './app.module';

@Component({
  selector: 'app-my-component',
  template: '<div>API URL: {{config.apiUrl}}</div>'
})
export class MyComponent {
  constructor(@Inject(APP_CONFIG) public config: any) {}
}
This code defines an Angular component called MyComponent which injects the configuration object using the 'APP_CONFIG' InjectionToken in its constructor. The injected config object is then available throughout the component, and its properties can be used in the component's template as demonstrated.