What is Custom pipe and how to create custom pipe in angular 4
- we have inbuilt pipes like lowercase, uppercase, slice, date etc which have their own functionality but if we want to create our custom login of filtering then we need to create custom filters.
- It has the @Pipe decorator with pipe metadata that has a name property.
- This value will be used to call this pipe in template expressions.
- It must be a valid JavaScript identifier.implement the PipeTransform interface’s transform method.
- This method takes the value being piped and a variable number of arguments of any type and return a
transformed (“piped”) value. - Custom pipe means is to generate hard-coded user-defined filter.
Example of angular 4 custom filter.
Step 1: First create custom pipe type script file in integrated terminal of visual studio code. Write following command
ng g pipe mypipe –flat
Step 2: Write following code into mypipe.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'mypipe' }) export class MypipePipe implements PipeTransform { transform(value: any, hobbie: string): any { if(hobbie === 'dancing'){ return "good hobbie is "+value; } else { return "bad hobbie is "+value; } } }
Step 3: Ensure that newly create pipe.ts reference has been added into app.module.ts.
Step 4: Please write following code into your own component(here is app.component.ts)
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { hobbies = []; constructor() { this.hobbies = ["singing","dancing","internet"]; } }
<h1>App Component</h1> <ul> <li *ngFor="let h of hobbies">{{ h | mypipe}}</li> </ul>
Step 5: Run your code using following command
ng serve –open
Output