*ngFor in Angular2

This repo contains a small snippet that compares ng-repeat of Angular 1.x with *ngFor of Angular 2.

Well, to start of with - ng-repeat directive will NOT be available in Angular 2. It has been replaced by a new directive i.e. *ngFor.

Here is a recap:

$scope.items = ['eat','sleep','work','eat']
<div ng-repeat="item in items track by $index">{{$index+1}} : {{item}}</div>
$scope.personDetails = {name:'Namita',age:'25'}
<div ng-repeat="(key, value) in personDetails">{{key}} : {{value}}</div>

Now, let's move to main agenda of this discussion i.e. *ngFor. Let's start.

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

ng-repeat created inherited child scope for each element of collection, while *ngFor creates local variable in the that block.

<input type="text" #inputText>

For the above case:

inputText would contain the reference of the element i.e. <input type="text">. inputText.value would contain the actual value entered in the input box.

 * Created by Namita Malik on 4/5/16.

import {Component} from 'angular2/core';

    selector: 'my-app',
    template: `
    <h2>Enter To Do Items Below:</h2>
    <input (keyup.enter)="onKey(todo)" #todo>
    <div *ngIf="toDoList.length>0">
        <p>Your To Do Items:</p>
    <div style="padding: 10px 0 0 0">
    <table width="300" border="1" cellpadding="5" style="text-align: center">
            <th>To Do Item</th>
        <tr *ngFor="#toDo of toDoList, #i=index, #last=last, #odd=odd, #even=even"  [ngClass]="{'odd-color':odd, 'even-color':even, 'last-color' : last }">

export class AppComponent {
    toDo = {
        item: ''
    title = 'My To Do List';
    toDoList = [];

    onKey(todo) {
        todo.value = '';

Note: It is not advisable to create grid structure using table tags but to keep the things simple I have used it here.

For example: odd-color class is applied on the row when item is odd. odd property returns a true or false on the basis of item index which is then assigned to local variable #odd.

In order to run the demo given in this repo, clone this repository. Go inside the repo and write npm install. This would bring required node modules for you.

Now, run open index.html in your favourite browser!

Follow Me




More Blogs By Me