My first Angular Pipe with TypeScript

Angular Beta 1 is released

After much hype the first Beta version of Angular (aka Angular2) was made available recently. It's a big change from AngularJS, so there's a lot to learn if you want to make the switch. The big question is, will there be significant adoption of Angular by the current users of AngularJS? The answer to that question depends on how developers feel about switching from JavaScript to TypeScript. In May 2014 I wrote about the potential of Dart but since then I've used AngularJS and JavaScript much more than Dart. For me Dart didn't live up to it's potential. It takes much more than new language features to persuade the JavaScript community to move away from JavaScript and onto something new.

But Angular is not about TypeScript! Developers can use JavaScript or Dart or TypeScript to develop Angular projects so we have to separate the discussion about the framework from the language? Wrong. I believe the move to Angular will be successful only when developers feel more productive. This means the right tooling needs to be in place to support the framework and the language - plus a critical mass of developers providing answers to questions. AngularJS provided increased productivity because of the way developers combined the framework, the language and the tools. Grunt, Gulp, bower and npm, depending on your preferences, created a more productive development environment. For Angular to succeed with TypeScript it will need to provide an even better development experience and this will require even better tooling.

My first Angular Pipe

Pipes in Angular replace the Filters used in AngularJS. The name change reflects the symbol used to pipe '|' the data through a function. The standard pipes are really useful, particularly the Date Pipe, but what appears to be missing from the standard set is the ability to create a subset of an array of objects based on the value of a property. In my case I wanted to display a list of Items based on their Category. AngularJS has a Filter called filter that takes an expression to do this. Here's my simple Angular Pipe using TypeScript:

import {Pipe} from 'angular2/core';
import {MyItem} from './myitem';

/*
 * Pipe to filter only the selected category of
 * MyItems
 */
@Pipe({name: 'category'})
export class CategoryPipe {
    transform(items: MyItem[], args:string[]) : any {
        if (items) {
            return items.filter(item => item.category == args[0]);
        }
    }
}

I used this Pipe in a template with an *ngFor loop:

<li *ngFor="#item of techItems | category: category">...</li>

The first time the pipe is called the Item[] is empty, then on the second call the array is populated as expected. I imagine this is something to do with the template lifecycle but I haven't investigated this yet.

This site uses cookies. Continue to use the site as normal if you are happy with this, or read more about cookies and how to manage them.

X