Angular

Building a Custom Pipe in Angular

Pipeline

We use Pipes to transform bound properties before displaying them in a view.  There are a number of built-in pipes, but what if we want to build our own custom pipe.  Here is how to do it.

Let’s say we are creating a list of products and we have a product code that is displayed like this 1234 ABC XYZ, and we want it to look like this 1234-ABC-XYZ. A custom pipe can accomplish this for us and it can be reused in the application later.

Pipe Class File

Create a class file called add-hyphens.pipe.ts  to the shared components folder of your application. Add the following code to the file.

Add the following code to the file.

import { Pipe, PipeTransform } from '@angular/core/';
@Pipe({
 name: 'addHyphens'
})

export class AddHyphensPipe implements PipeTransform {
 transform(value: string, character: string): string
 {
  return value.replace(character, '-');
 }
}

The import  statement is required to reference the Pipe and PipeTransform objects.  The @Pipe  decorator is required to define our class as a Pipe.  The name addHyphen  used for the @Pipe decorator is how we will reference the pipe in the HTML.  The class contains our logic for transforming the value.

That’s it, but before we can use in the HTML, we need to declare our Pipe in an Angular module so that our application knows where to find the Pipe addHyphens.  In our case it will be the app.module.ts.  We just need to add the  AddHyphensPipe  class to the declarations section of the module.

import { AddHyphensPipe } from './shared/add-hyphens.pipe'; 
... 
@NgModule({
 declarations:[
  AppComponent,
  ProductListComponent,
  AddHyphensPipe
], 
...

Now any components declared in this module is able to use our Pipe. We are now ready to use it in the HTML.

<td>{{ product.productCode | addHyphens: ' ' }}</td>

Using this, we can add hyphens to replace spaced in any string such as the product code in this example.

More Similar Posts

No results found.

Most Viewed Posts

No results found.

Menu