What are pipes in Angular and how are they used?
Pipes in Angular are a way to transform data in a declarative manner within a template. They allow you to apply transformations to expressions in your templates, such as formatting dates, converting values to uppercase or lowercase, or even performing complex mathematical calculations.
Pipes are used within templates by adding the pipe symbol (|
) followed by the name of the pipe. For example:
{{ date | date }}
{{ price | currency }}
{{ name | uppercase }}
In this example, the date
expression is being transformed by the date
pipe to display the date in a formatted manner, the price
expression is being transformed by the currency
pipe to display the price in a currency format, and the name
expression is being transformed by the uppercase
pipe to display the name in uppercase.
Pipes can also accept arguments, which can be used to control the output of the pipe. For example:
{{ date | date:'shortDate' }}
{{ price | currency:'USD':true }}
In this example, the date
pipe is being passed the argument 'shortDate'
, which determines the format of the date, and the currency
pipe is being passed the arguments 'USD'
and true
, which determine the currency and whether or not to display the currency symbol.
You can also create custom pipes in Angular to transform data in a specific way that is not available in the built-in pipes. To create a custom pipe, you create a class that implements the Pipe
interface and decorate it with the @Pipe
decorator.
Here is an example of a custom pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'squared'
})
export class SquaredPipe implements PipeTransform {
transform(value: number): number {
return value * value;
}
}
In this example, the SquaredPipe
class implements the PipeTransform
interface and is decorated with the @Pipe
decorator, which specifies the name of the pipe as 'squared'
. The transform
method is used to perform the transformation, in this case, squaring the input value. The custom pipe can then be used in templates like this:
{{ number | squared }}
This will display the result of squaring the number
expression.