Angular pipe – Create pipe
We can create pipe by ourselves
Angular prepare Pipe, PipeTransform class.
We can make our pipe using those classes.
Examples
Implements PipeTransform class.
Need to implement tranform method
grep.pipe.ts
This pipe receives array basically, if not array, just return value itself.
Using callback method, return filtered value(filter is callback method)
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'grep', pure: false }) export class GrepPipe implements PipeTransform { transform(values: any[], callback: (item: any) => boolean) { // value + callback if (!Array.isArray(values)) { return values; } return values.filter(callback); } }
How to use pipe
- Import pipe same as Component
- Use pipe
Import
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { GrepPipe } from './grep.pipe'; import { TrimPipe } from './trim.pipe'; import { TruncatePipe } from './truncate.pipe'; import { Nl2brPipe } from './nl2br.pipe'; import { GrepPipeTestComponent } from './greppipetest.component'; import { PipeTestComponent } from './pipetest.component'; @NgModule({ imports: [ BrowserModule, FormsModule ], declarations: [ GrepPipe, TrimPipe, TruncatePipe, Nl2brPipe, GrepPipeTestComponent, PipeTestComponent ], bootstrap: [ PipeTestComponent ] }) export class AppModule {}
Use Pipe
This is an test to use above pipe.
import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-root’,
template: `
- {{d}}
`
})
export class GrepPipeTestComponent {
data = [‘ABCDE’, ‘ABCD’, ‘ABC’, ‘EFGHI’, ‘J’];
myFilter(value: string) {
return String(value).length < 5;
}
}
[/javascript]