Angular - Pipes
The Pipe is a resource to transform a data to another format. The symbol of the pipe is the character '|', and to use this, you should put that inside the interpolation expression where the left side (integers, strings, arrays, and date) is your input and the right side is the function to transform the data. If necessary, you can use parameters as well.
Some examples are:
{ { birthday | date } } { {todaydate | date:'d/M/y'} } { {todaydate | date:'d/M/y' | uppercase} } | { {6589.23 | currency:"EUR"} } { {months | slice:2:6} }
Some examples of pipe function are: DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, Decimalpipe, Jsonpipe, Slicepipe and PercentPipe.
Custom Pipes
To create a custom pipe you should to create a file the name of your pipe (app.name.ts), to use the ‘@Pipe’ decorator and implement the method ‘transform’ from PipeTransform interface.
import {Pipe, PipeTransform} from '@angular/core'; @Pipe ({ name : 'name' }) export class NamePipe implements PipeTransform { transform(value: number): number { return //TODO your logic; } }
And to use you need to add your pipe in the declarations array of the AppModule and use in the template.
{ {yourdata | name} }
Pure and Impure Pipes
By default, every pipes are pure. It’s mean that the function is called just once, even if the data is updated.
The impure pipes are the pipes that are called every component change detection cycle. To make the pipe impure add the attribute ‘pure: false’ inside the ‘@Pipe’ metadata.