read

Recently, I started playing around with Angular 2 and stumbled across another cherry on top: the pipes API. Pipes are a significant improvement over filters in Angular 1.

Angular 1 Filters

Filters in AngularJS are an easy way to process data within expressions.

    <p>Upper: {{ 'hello' | uppercase }}</p>
    <!-- HELLO --> 

    <p>Lower: {{ 'Hello' | lowercase }}</p>
    <!-- hello -->

    <p>JSON: {{ {name: 'name'} | json }}</p>
    <!-- {name: 'name'} -->

And of course, the infamous filter filter:

    <li ng-repeat="friendObj in friends | filter:search:strict">

Okay, now forget about the filtering filter filter.

Angular 2 Pipes

Most of these filters carry over to Angular 2, only now they're called pipes. Pipes will likely replace your dependency on external libraries.

Angular 2 provides even better APIs for transforming common data. Let's look at a few examples:

Number

The number pipe takes a range of first digits before the period, and a range of second digits after. In this case, 2 before, 2-3 after the period.

    <p>{{3.142392 | number: '2.2-3'}}</p>
    <!-- 03.142 -->
Currency

The currency pipe is simple yet powerful. Possibly powerful enough to replace your reliance on an external library like Accounting.js.

    <!-- currency: currencyCode: useSymbol: number -->
    <p>{{42 | currency: 'USD': true: '.2-2'}}</p>
    <!-- $42.00 -->

    <p>{{42 | currency: 'USD': false: '.2-2'}}</p>
    <!-- USD42.00 -->

    <p>{{0.42 | currency: 'EUR': true: '.2-3'}}</p>
    <!-- €0.420 -->
Date

Finally let's look at a possible replacement for Moment.js, the date pipe.

Considering this.now = Date.now(), let's see the results.

    {{ now | date }}
    <!-- Aug 7, 2015 -->

    {{ now | date: 'shortTime' }}
    <!-- 4:18 PM -->

    {{ now | date: 'medium' }}
    <!-- Aug 7, 2015, 4:18:14 PM -->

    {{ someDate | date: 'mmss' }}
    <!-- 18:14 -->
LimitTo

limitTo filters out data. If we have a list, we can selectively choose what to display.

    this.list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Let's grab the first three only (3), then last three only (-3).

    <span*ng-for="#item of list | limitTo: 3">{{item}}</span>
    <!-- 1, 2, 3 -->

    <span *ng-for="#item of list | limitTo: -3">{{item}}</span>
    <!-- 8, 9, 10 -->

Example


Conclusion

Angular 2 has a similar look and feel to it's predecessor. Names change, but overall the new framework looks to be an improvement in nearly all areas.



Angular 2 Series
Event Emitters | Properties | Pipes | Meteor

Blog Logo

Shawn McKay

Published

Image

ShMcK

JavaScript Web Dev

Back Home