Pipes In Angular By Sagar Jaybhay

Custom and In-built Pipes in Angular By Sagar Jaybhay

Pipes are used for format the data. Built-in pipes: uppercase, lowercase, decimal, currency, percent.

We can also create custom pipes

Pipes_Sagar_Jaybhay_1

We can create custom pipes for that you need to add yourFileName.pipes.ts files and add code in that . For creating pipe you need to import 2 packages

import { Pipe,PipeTransform } from '@angular/core'

And on class need to include Pipe attribute

import { Pipe,PipeTransform } from '@angular/core'

@Pipe({
    name:'Summary'
})
export class SummaryText implements PipeTransform{
    transform(value: any, limit?:number) {
     if(!value)
     return null;

    limit=limit?limit:50;    
    
    return value.substr(0,limit)+'............';
    }
}

To create Pipe also you need to include PipeTransform interface and this interface has transform method. You need to implement this method in your code and then add this app.module.ts files declarations array.

Pipes_Sagar_Jaybhay_2.png

Then where you need to use that pipe you can use it.

import { Component} from '@angular/core'

@Component({
selector:'blog',
template:'<div> {{value|Summary:100}} </div>'
})
export class SummaryForBlog
{
value="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
}

In selector used Summary which is pipe name.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *