Thursday, May 12, 2016

Pipes in Angular2

Pipes are Angular 1.x filter being rethink. Pipes can be defined with special decorator @Pipe.
This entity can accept a value plus additional options parameters and return a transformed result.
By default you have available: DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe;

Valuable changes:
1) filter and orderBy are not present anymore in Angular 2 because:

  • they perform(ed) poorly on large datasets
  • they prevent aggressive minification.

2) There are now 2 types of pipes:
Pure pipes - the regular ones, think of puyre function in FP - without detectable side-effects.
Impure pipes - this guys can involve more stuff outside it's body
and angular executes an impure pipe during every component change detection cycle.

  •  AsyncPipe
  •  caching pipe

In Angular 1.x you will do:
  //in controller
  $filter('date')(myDate, 'yyyy-MM-dd');

  //in template
  {{value | date:'yyyy-MM-dd'}}

In Angular 2.x you have following steps:
1) Custom pipe declaration
  import {Pipe} from '@angular/core';

      name: "example"

  export class ExamplePipe{
      transform(value, [status]){

          return value.toLowerCase();

2) usage
  //component that uses ExamplePipe
  import {ExamplePipe} from './example-pipe';

    selector: 'todo-list',
    pipes: [ExamplePipe],
    constructor(private stringPipe: ExamplePipe) {}

    transformText(date) {
      return this.stringPipe.transform(myText);
  //or in the template
  <p>{{mytext | example}}</p>

More detailed Pipes overview:
Official docs:

No comments:

Post a Comment