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

<div>
    <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/>
</div>

Uppercase Pipe

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

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

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

 }

**********************
In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)
And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform {   
    transform(value:any, arg1:any, arg2:any, arg3:any):any {
}


1 comment:

Priya said...

This is most informative and also this post most user-friendly and super navigation to all posts. Thank you so much for giving this information to me
Angular JS Online training
Angular JS training in Hyderabad

Followers

Link