Monday 20 June 2016

ng-repeat in angular 2

Looping is very simple in Angular js 1, don't worry it is more simple in Angular js 2 as well with lot of performance improvement. Let us check first how it is in Angular 1.

JSON


$scope.data = [
 {
  name:'Prashobh',
  country:India
 },
 {
  name:'Abraham',
  country:US
 },
 {
  name:'Jhon',
  country:China
 }
]

Html


<div ng-repeat="d in data">
  <span>Name : {{ d.name }}</span>
  <span>Age : {{ d.country }}</span>
</div>

Now let us check how we can do the same using angular js 2

Typescript


export class sampleComponent {
    data: any[];
    constructor() {
        this.data = [{
               name:'Prashobh',
               country:India
             },
             {
              name:'Abraham',
              country:US
             },
             {
              name:'Jhon',
              country:China
             }
         ]
    }

I added JSON file inside the constructor itself for now, ideally it should be from service file, I am not going to explain those in this post.

Don't forget to import angular2/core in your typescript file.


import {Component} from 'angular2/core'

If you are facing any issue on setting up your angular 2 app, please check this reference How to start with Angular js 2

Html


<div *ngFor="let d of data">
  <span>Name : {{ d.name }}</span>
  <span>Age : {{ d.country }}</span>
</div>

Here * is important, without that it won’t work. Angular 2 is making use of powerful css and html properties.The let key is part of angular 2 template syntax.

Related Posts

1. How to start with Angular js 2

1 comment :

  1. what of if i have two [object][object]; and i want to list them at once using angular js...what should i do

    ReplyDelete