Using a Custom Pipe

We will create custom pipe by making use of shared component so that it will be available all over the app. It is similar to create other component. We need to create the class, export and import them, use pipe as a decorator, use interface and its method. Eg:

'convertToSpaces' is the pipe name that we are going to change the value in template
'PipeTransform' is the interface name
'transform' is the method name for 'PipeTransform' interface
'value: string' is the current value shown in template
'character: string' is the value we are about to replace with

Now, let's use custom pipe in our application. Since, custom pipe is somewhat general, we'll add them in 'shared' folder. Write the file named 'conver-to-spaces.pipe.ts' and add the following code:
import { Pipe, PipeTransform } from "@angular/core";

  name: 'convertToSpaces'
export class ConvertToSpacesPipe implements PipeTransform {
  transform(value: string, character: string) : string {
    return value.replace(character, ' ');

'value.replace' is the Javascript replace method and in this case replacing into empty space


Now, we have to add custom pipe in 'product-list.component.html' and import and add declaration in 'app.module.ts'

Share this

Related Posts