Does ngRepeat exist in Angular 2?

谁说我不能喝 提交于 2019-11-27 20:26:49

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>

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

import { NgFor } from 'angular2/angular2';

@View({ directives: [NgFor] })  

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!