Site icon Tutorial

Custom pipes

Go back to Tutorial

You can write your own custom pipes. Here’s a custom pipe named ExponentialStrengthPipe that can boost a hero’s powers:

src/app/exponential-strength.pipe.ts

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

/*

* Raise the value exponentially

* Takes an exponent argument that defaults to 1.

* Usage:

* value | exponentialStrength:exponent

* Example:

* {{ 2 | exponentialStrength:10 }}

* formats to: 1024

*/

@Pipe({name: ‘exponentialStrength’})

export class ExponentialStrengthPipe implements PipeTransform {

transform(value: number, exponent: string): number {

let exp = parseFloat(exponent);

return Math.pow(value, isNaN(exp) ? 1 : exp);

}

}

This pipe definition reveals the following key points:

The @Pipe decorator allows you to define the pipe name that you’ll use within template expressions. It must be a valid JavaScript identifier. Your pipe’s name is exponentialStrength.

Go back to Tutorial

Exit mobile version