This tutorial is out of date and no longer maintained.
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.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<p>My name is <strong>{{ name | uppercase }}</strong>.</p>',
})
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.
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(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
}
To use this pipe, let modify our app component, like this:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<p>My name is <strong>{{ name | capitalize }}</strong>.</p>', // change to use capitalize pipe
})
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.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { CapitalizePipe } from './capitalize.pipe'; // import our pipe here
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, CapitalizePipe ], // include capitalize pipe here
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.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!