Angular 2 will contain many new changes and improvements over Angular 1.x This post will cover the new ngFor syntax and a simple comparison of version 1 ng-repeat to version 2 ngFor. Note Angular 2 is still in development and the API’s are actively changing. At the writing of this post Angular 2 is at RC 1. To get an idea on the progress of the project check out Is Angular 2 Ready?

First we will take a look at a simple Angular 1.x repeater that displays the index of the repeated item and the item value.



<!-- Angular 1.x -->
<ul>
  <li ng-repeat="item in items">
    {{$index}} {{item}}
  </li>
</ul>


Here is the new ngFor syntax.



<!-- Angular 2.0 -->
<ul>
  <li *ngFor="let item of items; let i = index">
    {{i}} {{item}}
  </li>
</ul>


The new syntax has a couple of things to note. The first is *ngFor. The * is a shorthand for using the new Angular 2 template syntax with the template tag. This is also called a structural Directive. It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag. The template tag prevents the browser from reading or executing the code within it.



<!-- Angular 2.0 longhand ngFor -->
<template ngFor let-item="$implicit" [ngForOf]="items" let-i="index">
  {{i}} {{item}}
</template>


So below is the typical syntax for an Angular 2 list.



<ul>
  <li *ngFor="let item of items; let i = index">
    {{i}} {{item}}
  </li>
</ul>


Looking back at our ngFor the next interesting thing to note is let item of items;. The let key is part of the Angular 2 template syntax. let creates a local variable that can be referenced anywhere in our template. So in our case we are creating a local variable let item.

The let i creates a template local variable to get the index of the array. If you do not need access to the index in your list the ngFor simply boils down to the following code.



<ul>
  <li *ngFor="let item of items">
    {{item}}
  </li>
</ul>


One thing to note the camelCase syntax was introduced in Alpha 52. A new custom HTML parser was introduced that allowed camelCasing in templates to replace the kebab-case syntax.

Track By

Angular 2 also includes the trackBy feature from Angular 1.x that allows performance improvements in our list rendering by tracking a unique identifier on our list items. The trackBy in Angular 2 is slightly different than Angular 1. To use track by you must pass a function as a parameter from your component.



<ul>
  <li *ngFor=" let item of items; trackBy: trackByFn;">
    {{item}}
  </li>
</ul>




// Method in component class
trackByFn(index, item) {
  return item.id;
}


The new angular syntax will allow Angular to work with native web components and gain the benefits of using Web Components. Angular 2 will bring many exciting improvements over angular 1 and will soon allow us to create even more scalable web applications.

Demo