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.




Tuesday, 26 June 2018

Angular – Pipes

Every application starts out with what seems like a simple task: get data, transform them, and show them to users. Getting data could be as simple as creating a local variable or as complex as streaming data over a WebSocket.
Once data arrive, you could push their raw toString values directly to the view, but that rarely makes for a good user experience. For example, in most use cases, users prefer to see a date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time).
Introducing Angular pipes, a way to write display-value transformations that you can declare in your HTML.

Using pipes:
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
src/app/hero-birthday1.component.ts
import { Component } from '@angular/core';

  selector: 'app-hero-birthday',
  template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988
}
Inside the interpolation expression, you flow the component's birthday value through the pipe operator ( | ) to the Date pipe function on the right. All pipes work this way.

Built-in pipes:
Angular comes with a stock of pipes such as DatePipeUpperCasePipeLowerCasePipeCurrencyPipe, and PercentPipe. They are all available for use in any template.

Parameterizing a pipe:
A pipe can accept any number of optional parameters to fine-tune its output. To add parameters to a pipe, follow the pipe name with a colon ( : ) and then the parameter value (such as currency:'EUR'). If the pipe accepts multiple parameters, separate the values with colons (such as slice:1:5)
Modify the birthday template to give the date pipe a format parameter. After formatting the hero's April 15th birthday, it renders as 04/15/88:
src/app/app.component.html
<p>The hero's birthday is {{ birthday | date:"MM/dd/yy" }} </p>
Write a second component that binds the pipe's format parameter to the component's format property. Here's the template for that component:
src/app/hero-birthday2.component.ts (template)
  <p>The hero's birthday is {{ birthday | date:format }}</p>
  <button (click)="toggleFormat()">Toggle Format</button>
`
You also added a button to the template and bound its click event to the component's toggleFormat() method. That method toggles the component's format property between a short form ('shortDate') and a longer form ('fullDate').
src/app/hero-birthday2.component.ts (class)
export class HeroBirthday2Component {
  birthday = new Date(1988, 3, 15); // April 15, 1988
  toggle = true; // start with true == shortDate

  get format()   { return this.toggle ? 'shortDate' : 'fullDate'; }
  toggleFormat() { this.toggle = !this.toggle; }
}
As you click the button, the displayed date alternates between "04/15/1988" and "Friday, April 15, 1988".






Pre-defined date pipe format options:
Examples are given in en-US locale.
  • 'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
  • 'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
  • 'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
  • 'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
  • 'shortDate': equivalent to 'M/d/yy' (6/15/15).
  • 'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
  • 'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
  • 'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
  • 'shortTime': equivalent to 'h:mm a' (9:03 AM).
  • 'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
  • 'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
  • 'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).


Chaining pipes:
You can chain pipes together in potentially useful combinations. In the following example, to display the birthday in uppercase, the birthday is chained to the DatePipe and on to the UpperCasePipe. The birthday displays as APR 15, 1988.
src/app/app.component.html
The chained hero's birthday is
{{ birthday | date | uppercase }}
This example—which displays FRIDAY, APRIL 15, 1988—chains the same pipes as above, but passes in a parameter to date as well.
src/app/app.component.html
The chained hero's birthday is
{{  birthday | date:'fullDate' | uppercase }}