Custom Pipes

Custom pipe create using @pipe decorator with pipe metadata. In these article we discuss on how to use pipe decorator and how to crate custom pipe easily. In pipe decorator we must transform method to use from “PipeTransform” Class.


In below example we discuss if image isnot assign then we need to display default image.
In our html we can write below code.

<img class="img-responsive"[src]="myimage | loadimage:'http://via.placeholder.com/350x150' />

In above example we need to create “loadimage” custom pipe which load first default place-holder then it replace with original image when loaded.
Let’s create custom pipe called “loadimage”


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

export class LoadImagePipe implements PipeTransform {

transform(value: string, default: string): string {
    let image = "";
    if (value) {
      image = value;
    } else {
      image = default;
    }
     return image;
  }

}



In above class we need to import pipe & PipeTransform from the angular core. we need to create transform method which has first parameter value which define before pipe(|) in our example it’s “myimage”. second parameter which we have pass after colon(:).

You can pass multiple value pass in pipe using colon sign.. Like below example.


loadimage :value1:value2:value3

Form these way you can easily create custom pipe with multiple value. If you have in issue with it then please comment it here.

Spread the love
  • 18
  •  
  •  
  •  
  • 1
  •  
  •  
  •