Wednesday, 27 June 2018

Angular - Custom pipes

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:
  • A pipe is a class decorated with pipe metadata.
  • The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.
  • There will be one additional argument to the transform method for each parameter passed to the pipe. Your pipe has one such parameter: the exponent.
  • To tell Angular that this is a pipe, you apply the @Pipe decorator, which you import from the core Angular library.
  • 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.
The PipeTransform interface:
The transform method is essential to a pipe. The PipeTransform interface defines that method and guides both tooling and the compiler. Technically, it's optional; Angular looks for and executes the transform method regardless.
Now you need a component to demonstrate the pipe.
src/app/power-booster.component.ts
import { Component } from '@angular/core';

  selector: 'app-power-booster',
  template: `
    <h2>Power Booster</h2>
    <p>Super power boost: {{2 | exponentialStrength: 10}}</p>
  `
})
export class PowerBoosterComponent { }








Note the following:
  • You use your custom pipe the same way you use built-in pipes.
  • You must include your pipe in the declarations array of the AppModule.
  • You must register custom pipes. If you don't, Angular reports an error. Angular CLI's generator registers the pipe automatically.




1 comment:

  1. Just found your post by searching on the Google, I am Impressed and Learned Lot of new thing from your post.

    KissAnime alternatives

    ReplyDelete