Pipe is a building block in Angular. We use pipe to format data in Angular. We have got some build-in pipes like Uppercase, Lowercase, Decimal, Currency, Percent. We will learn How to create custom Pipe in Angular in this post. Before going to create custom pipe let’s get some example of build-in pipes using interpolation.
- Uppercase: {{ “this is text” | uppercase }} => THIS IS TEXT
- Lowercase: {{ “THIS IS TEXT” | lowercase }} => this is text
- Decimal: {{ 4.0546 | number:’1.2-2′ }} => 4.06
- Currency: {{ 160.26 | currency }} => USD160.26
- Date: {{ new Date(2019, 9, 5) | date:’shortDate’ }} => 10/5/2019
Custom pipe
Now lets learn how to create custom pipe in Angular. We will be creating a summary pipe, which will summarize a long text content to some limited character provided as option or 50 character to default.
- Create a new file using standard naming convention. for example: summary.pipe.ts
- Import Pipe and PipeTransform from @angular/core.
- Export a class just like Module or Component implementing PipeTransform.
- Decorate class with @Pipe and provide a name to this pipe. In our case we are giving summary.
- Add unimplemented method to the class, transform(value: any, args?: any): any
After following above step, you could have reached up to provided below. If not, please do check.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'summary'})
export class SummaryPipe implements PipeTransform {
transform(value: any, args?: any) {
}
}
Now complete transform method according to your need and return final value. Below is complete code of summary pipe.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'summary'})
export class SummaryPipe implements PipeTransform {
transform(value: string, args?: any) {
if(!value) return null;
return value.substr(0, (limit)?limit:50) + '...';
}
}
This pipe will return summary of paragraph upto specified limit or max of 50.
Comments
Post a Comment