Skip to content
On this page

Custom provider in @NgModule and @Component

In Angular, we can provide a custom provider by using the provide property in the @NgModule decorator or the providers property in the @Component decorator. This allows us to specify a custom token and the corresponding provider value.

Here's how we can provide a custom provider in Angular:

  1. Import the necessary dependencies:
typescript
import { NgModule } from '@angular/core';
import { MyCustomService } from './my-custom.service';
  1. Create a custom token for your provider. This token can be a string or an instance of the InjectionToken class from @angular/core. For example:
typescript
import { InjectionToken } from '@angular/core';

export const MY_CUSTOM_TOKEN = new InjectionToken<string>('MyCustomToken');
  1. Define your custom provider using the provide property within the @NgModule decorator or the providers property within the @Component decorator. Here's an example of providing the custom token and associating it with your custom service:
typescript
@NgModule({
  providers: [
    { provide: MY_CUSTOM_TOKEN, useClass: MyCustomService }
  ]
})
export class AppModule { }
  1. In the component or service where we want to use the provided value, inject the custom provider using the @Inject decorator and the custom token. For example:
typescript
import { Component, Inject } from '@angular/core';
import { MY_CUSTOM_TOKEN } from './my-custom.token';

@Component({
  selector: 'app-my-component',
  template: '...',
  providers: [{ provide: MY_CUSTOM_TOKEN, useClass: MyCustomService }]
})
export class MyComponent {
  constructor(@Inject(MY_CUSTOM_TOKEN) private customService: MyCustomService) {
    // Use the custom service...
  }
}

In the example above, the MyCustomService is provided using the custom token MY_CUSTOM_TOKEN at both the module level and the component level. This allows us to provide a different instance of the service at the component level if needed.