P.Brian.Mackey
P.Brian.Mackey

Reputation: 44295

When is it useful to inject a custom pipe?

According to the angular docs:

If you choose to inject your pipe into a class, you must provide it in the providers array of your NgModule.

Given exponential-strength.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'exponentialStrength' })
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent?: number): number {
    return Math.pow(value, isNaN(exponent) ? 1 : exponent);
  }
}

I am able to use this custom pipe in a template by adding the declaration to app.module.ts:

@NgModule({
  declarations: [
    AppComponent,
    ExponentialStrengthPipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],

E.G. in app.component.html

<div>
  {{ 2 | exponentialStrength:10 }}
</div>

I'm confused by Angular's documentation. It doesn't mention the need to add the custom pipe to declarations in the documentation. The documentation only mentions providers.

Is it useful in some cases to inject a pipe when the declaration works just fine? I'm having trouble imagining a use case where I would actually put a pipe into providers array. And would I still need to define the custom pipe in declarations in such a case?

Upvotes: 1

Views: 988

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71961

The docs state if you want to inject a pipe in your component to use as a service, you need to add it to the providers. This could come of use, if you want to use certain functions in your pipe (which you better just move to a util file).

For all intents and purposes you should not add it to the providers, unless you are a bit lazy :)

Upvotes: 1

Related Questions