AangularJS 4 ngfor example
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>
0 comments:
Post a Comment