📅  最后修改于: 2023-12-03 14:59:18.721000             🧑  作者: Mango
In Angular 10, a Pipe is the way to transform the data before it reaches the view. A Pipe is a class decorated with @Pipe() decorator and implements PipeTransform interface.
Pipes can be used in the template expressions to format, filter or transform the data before rendering. Pipes can be chained together to perform multiple transformations.
{{expression | pipeName:param1:param2}}
<p>Today is {{date | date: 'dd/MM/yyyy'}}</p>
In this example, the date pipe formats the date before it is rendered.
Custom pipes can be created by implementing the PipeTransform interface and decorating the class with @Pipe decorator. The Pipe decorator takes the name of the pipe as an argument.
@Pipe({
name: 'myPipeName'
})
export class MyPipe implements PipeTransform {
transform(value: any, arg1: any, arg2: any): any {
// transform the value
return transformedValue;
}
}
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: any): any {
if (value) {
return value.split('').reverse().join('');
}
}
}
In this example, a custom pipe called reverse
has been created to reverse the given string.
Angular provides some built-in pipes that can be used to format, filter and transform the data.
The DatePipe is used to format the date. The date pipe takes a format string argument to format the date.
<p>Today is {{today | date:'dd/MM/yyyy'}}</p>
The UpperCasePipe and LowerCasePipe are used to transform the text to upper case and lower case respectively.
<p>{{'HELLO WORLD' | lowercase}}</p>
<p>{{'hello world' | uppercase}}</p>
The DecimalPipe is used to format the decimal numbers. The decimal pipe takes a format string argument to format the decimal numbers.
<p>{{3.14159265 | number: '1.2-2'}}</p>
The CurrencyPipe is used to format the currency values. The currency pipe takes a currency code argument to format the currency values.
<p>{{1000 | currency: 'USD'}}</p>
In conclusion, Pipes are used to transform the data before rendering it in the view. Custom pipes can be created by implementing the PipeTransform interface and decorating the class with the @Pipe decorator. Angular provides some built-in pipes such as DatePipe, UpperCasePipe, LowerCasePipe, DecimalPipe and CurrencyPipe.
Happy coding!