NgRepeat vs *ngFor

This blog demonstrates difference between NgRepeat and *ngFor.

Download as .zip Download as .tar.gz View on GitHub

#*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"> : </div>
$scope.personDetails = {name:'Namita',age:'25'}
<div ng-repeat="(key, value) in personDetails"> : </div>

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

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

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';

@Component({
    selector: 'my-app',
    template: `
    <h1></h1>
    <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>
    <div style="padding: 10px 0 0 0">
    <table width="300" border="1" cellpadding="5" style="text-align: center">
        <tr>
            <th>Index</th>
            <th>To Do Item</th>
        </tr>
        <tr *ngFor="#toDo of toDoList, #i=index, #last=last, #odd=odd, #even=even"  [ngClass]="{'odd-color':odd, 'even-color':even, 'last-color' : last }">
            <td></td>
            <td></td>
        </tr>
    </table>
    </div>
    `
})

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

    onKey(todo) {
        this.toDoList.push(todo.value);
        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

Github

Twitter

LinkedIn

More Blogs By Me