CT14.IT
CT14.IT

Reputation: 1737

Does ngRepeat exist in Angular 2?

I've read various issue tracker entries in relation to Angular 2 and its implementation of ng-repeat, but as it stands I haven't actually worked out if it actually exists yet.

Is it possible to use ng-repeat in angular 2?

Upvotes: 36

Views: 52371

Answers (4)

Storytellerr
Storytellerr

Reputation: 819

for angular 8 and above the correct syntax is

<ul>
    <li *ngFor="let hero of heroes">
      {{ hero }}
    </li>
</ul>

Upvotes: 2

rcd
rcd

Reputation: 4290

Angular 2.0 Release

my-component.ts:

import { Component } from 'angular2/core';

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})
export class MyComponent{
  public values: number[] = [1, 2, 3];
}

my-component.html:

<div *ngFor='let value of values; trackBy: index;'>
  {{ value }}
</div>

Upvotes: 54

CT14.IT
CT14.IT

Reputation: 1737

UPDATE: this comment is now out of date, please see accepted answer

OK, CURRENTLY, the following works.

/// <reference path="typings/angular2/angular2.d.ts" />

import {Component, View, For, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'itemlist'
})
@View({
  directives: [For]
  template: `<h2 (click)="onClick()">Hello {{ name }}</h2><ul><li *for="#item of items">{{item.name}}</li></ul>`
})
// Component controller
class ItemList {
  name: string;
  items: array;

  constructor() {
    this.name = 'Sub';
    this.items = [];
    this.addItem("Dog 0");
    this.addItem("Dog 1");
    this.addItem("Dog 2");
  }

  addItem(name){
    this.items.push({id: this.items.length, name: name});
  }

  onClick() {
    console.log(this.items);
    this.addItem("Dog "+this.items.length);
  }
}

What I was missing

You need to import For (line 3)

You need to declare your dependency of For for the component in question (line 9)

The correct syntax for "ng-repeat" is CURRENTLY *for="#item of items"

It seems to have changed quite a bit already during developing so I would not be surprised if it changes again.

Upvotes: 3

Ajden Towfeek
Ajden Towfeek

Reputation: 387

From alpha 28 to 30 it's the following syntax:

import { NgFor } from 'angular2/angular2';

@View({ directives: [NgFor] })  

<div *ng-for="#item of items">

Upvotes: 3

Related Questions