Angular 2 NgFor Example

Angular 2 NgFor directive repeats the part of a template for each item in an iterable.

angular 2 ngfor example
angular 2 ngfor example
try angular 2 ngfor
try angular 2 ngfor

live example and resources at the end of the article

Here are some local variables that NgFor provides:

  • index :current iteration (1 , 2 , 3 ….n)
  • last : Boolean that indicates if an item is the last iteration.
  • even : Boolean if the item has an even index.
  • odd : Boolean if the item has an odd index.

 

When the iterator changes NgFor changes the DOM, it adds, removes, and reorders new parts to the DOM depending on the number of items (e.g. add new item, remove an item).

NgFor Example :

/**
 * Created by Tareq Boulakjar. from angulartypescript.com
 */
import {Component} from 'angular2/core';
import {CORE_DIRECTIVES} from 'angular2/common';

/*Angular 2 NgFor Example*/
@Component({
    selector: 'my-app',
    template:`
                <div>
                     <h3>Angular 2 NgFor Example</h3>

                            <ul>
                              <li *ngFor="#item of carsList; #i = index">
                               <span class="car-title">{{i}}. {{item}}</span>
                              </li>
                            </ul>
                </div>
             `,
    styles:[`
                .car-title {
                    color: #00b0e8;
                }

            `],
    directives: [CORE_DIRECTIVES]
})
export class Angular2NgFor {
    carsList:Array;
    constructor() {
        this.carsList = ['BMW Serie 1', 'BMW Serie 2', 'BMW Serie 3', 'Angular Car', 'Angular 2 iCar'];
    }

}

our example uses typescript as programming language.

angular 2 ngfor