In angular 1.* we used to use ng-repeat pretty heavily like
Now with angular 2 we achieve same thing with with ngFor
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
What is this * for?
As you can see there’s no more ng-repeat, it’s ngFor now. why the asterisk? The answer to that is, it’s syntactic sugar.
ngFor can only be applied to a
*ngFor is the short form that can be applied to any element and the
<template> element is created implicitly behind the scene. The
* makes it easier to read and write directives that modify HTML layout with the help of templates.
NgSwitch all add and remove element subtrees that are wrapped in
*ngFor undergoes a transformation like shown below
Here’s the same after transporting the ngFor to the template directive:
And here it is expanded further into a tag wrapping the original element:
When Angular sees the asterisk (*) in ngFor, it will use its DOM element as template to render the loop.
Moreover *ngFor has more properties i.e index, first, last , even, odd we can get the value of index per iteration, can get the last value or odd, even index too using local variables. here is working example for the same:
NgFor provides several exported values that can be aliased to local variables:
- index will be set to the current loop iteration for each template context.
- first will be set to a boolean value indicating whether the item is the first one in the iteration.
- last will be set to a boolean value indicating whether the item is the last one in the iteration.
- even will be set to a boolean value indicating whether this item has an even index.
- odd will be set to a boolean value indicating whether this item has an odd index.
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.