Friday, January 19, 2018

Pipes in Angular 2

Pipes used to format data. A pipe takes the data and transforms this input to the desired output.

There are many built-in pipes in Angular 2.

Date Pipes

    <h4>Date Pipe Example</h4> 
    <b>Date format:</b> My joining Date is {{joiningDate | date}}.<br/> 
    <b>Specific Date Format:</b> My joining Date is {{joiningDate | date:"dd/MM/yyyy"}}<br/> 

Uppercase Pipe

    <h4>Upper Case Pipe Example</h4> 
    My name is {{name | uppercase}}! 

You can write your own custom pipes. Here's a custom pipe named ExponentialStrengthPipe

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);

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.

And component is

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 { }

No comments: