Angular ngFor syntax
The latest Angular has 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 the latest ngFor
.
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 -->
<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 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 longhand ngFor -->
<template ngFor let-item="$implicit" [ngForOf]="items" let-i="index">
{{i}} {{item}}
</template>
So below is the typical syntax for an Angular 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 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 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 newer versions of Angular 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 will bring many exciting improvements over Angular 1 and will soon allow us to create even more scalable web applications.