Wednesday, December 9, 2020

Custom Pipe in Angular With Example

Though there are many Angular built-in pipes for data transformation but Angular framework also gives you an option to create a custom pipe to cater to custom data transformation. In this tutorial we’ll see how to create a custom pipe in Angular.

Creating custom pipe in Angular

To mark a class as a pipe apply the @Pipe decorator to the class. In the name attribute of the of @Pipe provide the name of the pipe. Use name in template expressions as you would for a built-in pipe.

Your custom pipe class should also implement the PipeTransform interface.

interface PipeTransform {
  transform(value: any, ...args: any[]): any
}

In the implementation of the transform() method logic for data transformation has to be written. Angular invokes the transform method with the value of a binding as the first argument, and any parameters as the second argument in list form.

Structure of the custom pipe class is as given below.

@Pipe({
  name:'testPipe'
})
export class PipeClassName implements PipeTransform{
  transform(value: any, ...args: any[]): any{
    ...
    ...
  }
}

Then you can use your custom pipe like any other Angular built-in pipe.

{{ user.firstName | testPipe }}    

Angular custom pipe examples

We’ll create a custom pipe to sort the data where you should be able to provide the field on which you want to sort the data. So, if yo have data as displayed here, you should be able to sort it on firstName, lastName and so on by passing the appropriate field.

Angular pipe

Custom pipe class (sort.pipe.ts)

You can create Custom pipe class yourself or you can generate it from Angular CLI using the command- ng generate pipe pipe_name

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

@Pipe({
  name:'sort'
})
export class SortPipe implements PipeTransform{
  transform(value: any, key: string): any {
    return value.sort((val1, val2) => {
      if(val1[key] > val2[key]){
        return 1;
      }else if(val1[key] < val2[key]){
        return -1;
      }else{
        return 0;
      }
    })
  }  
}

Important points to note here-

  1. Class is decorated with @Pipe decorator and name given to the pipe is sort.
  2. In the transform method value is the value of the element this pipe is bound to. There is one parameter too thus making it a parameterized pipe.
  3. Since value is of type array here so we can use sort method of the array to sort the values. Comparison logic is given with in the sort method.

Component class (app.component.ts)

In the component class there is an array users.

import { CurrencyPipe, DatePipe, formatDate } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
})
export class AppComponent{
  users = [{
      firstName: 'John',
      lastName: 'Doe',
      dept: 'Finance',
      salary: 5000,
      doj: new Date('2015-12-11')
    }, 
    {
      firstName: 'Amy',
      lastName: 'Watson',
      dept: 'HR',
      salary: 8000,
      doj: new Date('2013-07-23')
    }, 
    {
      firstName: 'Shrishti',
      lastName: 'Sharma',
      dept: 'IT',
      salary: 10000,
      doj: new Date('2019-10-20')
    }
  ]
}

Template (app.component.html)

<div class="container">
  <h1>User Details</h1>
  <table class="table table-sm table-striped m-t-4">
    <thead class="thead-dark">
      <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Department</th>
      <th>Salary</th>
      <th>Joining Date</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let user of users | sort:'firstName'">
      <td>{{user.firstName}}</td>
      <td>{{user.lastName}}</td>
      <td>{{user.dept}}</td>
      <td>{{user.salary}}</td>
      <td>{{user.doj | date:'dd/MM/yyyy'}}</td>
    </tr>
  </tbody>
  </table>
</div>

As you can see sort pipe is used here with in the ngFor directive. Since it is bound with the users array so that is passed as the value. Parameter passed with the pipe here is ‘firstName’ so sorting is done on firstName field.

Angular custom pipe example

Adding pipe declaration to the AppModule

If you have created the Pipe class yourself then you do need to add it to the AppModule class youself too. Add the class in the declarations array.

@NgModule({
  declarations: [
    AppComponent,
    SortPipe
  ],
  ...
  ...
})
export class AppModule { }

That's all for this topic Custom Pipe in Angular With Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Pure and Impure Pipes in Angular
  2. Using Angular Pipes in Component or Service Classes
  3. Async Pipe in Angular With Examples
  4. Custom Async Validator in Angular Template-Driven Form
  5. What is Client Side Routing in Angular

You may also like-

  1. Angular Disable Button Example
  2. Angular Form setValue() and patchValue()
  3. Angular Event Binding With Examples
  4. How to Setup Angular
  5. collect() Method And Collectors Class in Java Stream API
  6. Association, Aggregation And Composition in Java
  7. Connection Pooling Using Apache DBCP in Java
  8. Magic Methods in Python With Examples

No comments:

Post a Comment