Create a Globally Available Custom Pipe in Angular 2

In this tutorial, we will learn about what is pipe, how to build a custom pipe, how to make the pipe available application-wide. Live example here in plnkr.
Angular 2 comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. They are all immediately available for use in any template.
For example, utilize the uppercase pipe to display a person’s name in capital letter.
app.component.ts
import { Component } from ‘@angular/core’; @Component({ selector: ‘my-app’, template: ‘
My name is {{ name | uppercase }}.
‘, }) export class AppComponent { name = ‘john doe’; }
The output of the example above is My name is John Doe.
Now if you would like to capitalize the first letter of each word, you can create a custom pipe to do so.
capitalize.pipe.ts
import { Pipe, PipeTransform } from ‘@angular/core’; @Pipe({name: ‘capitalize’}) export class CapitalizePipe implements PipeTransform { transform(value: string, args: string[]): any { if (!value) return value; return value.replace(/wS*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } }
To use this pipe, let modify our app component, like this:
app.component.ts
import { Component } from ‘@angular/core’; @Component({ selector: ‘my-app’, template: ‘
My name is {{ name | capitalize }}.
‘, }) export class AppComponent { name = ‘john doe’; }
The output of the example above is My name is John Doe.
Now imagine that you have a pipe that you will use in almost all of your components (e.g., a translate pipe), how can we make it globally available just like the built-in pipes?
There’s a way to do it. We can include the pipe in the application module of our application.
app.module.ts
import { NgModule } from ‘@angular/core’; import { BrowserModule } from ‘@angular/platform-browser’; import { AppComponent } from ‘./app.component’; import { CapitalizePipe } from ‘./capitalize.pipe’; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, CapitalizePipe ], bootstrap: [ AppComponent ] }) export class AppModule { }
Angular Module is a great way to organize the application and extend it with capabilities from external libraries. It consolidate components, directives and pipes into cohesive blocks of functionality. Refer to Angular documentation.
Now, we can run our application and check the page result.