Thursday, November 29, 2018

Angular Custom Pipes

In the previous posts we saw about the built-in pipes in Angular, their syntax, usage, chaining etc. Angular also provides us the ability to create our own custom pipes to suite our requirement. When we cannot use any of the built-in pipes for our requirement we can create a custom pipe. Also for larger applications, create custom pipes helps in reusing code/functionality.

Custom pipes are nothing but classes like Components and custom Directives, Custom pipe classes use the @Pipe decorator. The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.

While creating the custom pipe class, use the @Pipe decorator and specify the name of the custom pipe as follows.
@Pipe({name: ''})

The custom pipe class should implement the interface PipeTransform and provide an implementation for its transform() method. The transform() which is the key for the pipe implementation. This method contains the transformation logic. The transform method gets the input value passed to the pipe, the method can be used to transform the input value. The return value from the transform() function will be the final output from the pipe.

Below is the skeleton syntax for creating a custom Pipe.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'customPipeName'})
export class customPipe implements PipeTransform {
  transform(input: number, exponent: string): number {
    // Pipe Transformation logic goes here
  }
}

Search Flipkart Products:
Flipkart.com

1 comment:

Priya said...

Thank you so much for your post. This post really helps me a lot and I have learned some new things from your blog. I am bookmarking your blog for a future visit.
Angular JS Online training
Angular JS training in Hyderabad