Custom Pipe
Step 1 - Create Custom Pipe
import {Pipe, PipeTransform} from ‘angular2/core’;
@Pipe({ name: ‘summary’ })
export class SummaryPipe implements PipeTransform
{
transform(value: string, args: string[]) { }
}
Step 2 - In the host component
@Component({
pipes: [SummaryPipe]
template: `{{ description | summary }}`
})
Step 3 - Register pipe to module
@NgModule({
declarations: ['SummaryPipe']
})
Demo
Create Pipe
import { Pipe, PipeTransform } from 'angular2/core';
@Pipe({
name: 'summary'
})
export class SummaryPipe implements PipeTransform {
transform(value: string, args: string[]) : any {
let limit = (args && args[0] ) ? parseInt(args[0]): 30;
if(value.length > limit){
return value.substring(0, limit) + '...';
}
return value;
}
}
Using Pipe
import {Component} from "angular2/core";
import {SummaryPipe} from './shared/summary.pipe';
@Component({
template: `
<div>{{ description | summary:5 }}</div>
`
})
export class MyApp{
description = 'An attribute directive minimally requires';
}
Demo 2
<p> "Hemant" pipe greet </p> // Hello Hemant
<p> "Hemant" pipe greet:'Mr' </p> // Hello Mr. Hemant
import { Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'greet'
})
export class GreetPipe implements PipeTransform{
transform(name: string, prefix = ''){
return `${prefix} ${name}`;
}
}
Last updated
Was this helpful?