# Generic Injection Token

In 
Published 2024-01-06

This tutorial explains Generic Injection Token in Angular.

In Angular, Injection Tokens are used to configure and control the behavior of the Dependency Injection (DI) system. Generic Injection Tokens, introduced in Angular version 4.0, allow you to create more flexible and reusable tokens with generic types.

Here's how you can define and use a generic injection token in Angular:

# Define a Generic Injection Token

You can use the InjectionToken class to define a generic injection token. The generic type T specifies the type of the value associated with the token.

// my-tokens.ts
import { InjectionToken } from '@angular/core';

export const MY_GENERIC_TOKEN = new InjectionToken<string>('MyGenericToken');

In this example, MY_GENERIC_TOKEN is a generic injection token of type string. The string parameter passed to the InjectionToken constructor is a description used for debugging purposes.

# Provide a Value for the Token

In your Angular module or component, you can provide a value for the generic injection token using the useValue property in the providers array.

// app.module.ts
import { NgModule } from '@angular/core';
import { MY_GENERIC_TOKEN } from './my-tokens';

const myString = 'This is a generic token value';

@NgModule({
  providers: [
    { provide: MY_GENERIC_TOKEN, useValue: myString },
    // Other providers
  ],
})
export class AppModule {}

Here, we provide the value 'This is a generic token value' for the MY_GENERIC_TOKEN token using the useValue property.

# Inject the Generic Injection Token

You can inject the generic injection token into a component or service constructor using Angular's dependency injection system.

// some-component.ts
import { Component, Inject } from '@angular/core';
import { MY_GENERIC_TOKEN } from './my-tokens';

@Component({
  selector: 'app-some-component',
  template: '<p></p>',
})
export class SomeComponent {
  constructor(@Inject(MY_GENERIC_TOKEN) public myTokenValue: string) {}
}

In this example, MY_GENERIC_TOKEN is injected into the SomeComponent constructor, and the associated value is assigned to the myTokenValue property.

Using generic injection tokens provides a way to define and use tokens with specific types, allowing for more type-safe and reusable code within your Angular application. It's particularly useful when you want to inject configuration values or other runtime parameters into your components and services.