angularjs ng repeat——Angular 2中还存在ngRepeat吗?



我已经阅读了与Angular 2及其ng-repeat实现相关的各种问题跟踪条目,但就目前而言,我还没有弄清楚它是否真的存在。

有可能在角2中使用ng-repeat吗?

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>

从alpha 28到alpha 30的语法如下:

import { NgFor } from 'angular2/angular2';
@View({ directives: [NgFor] })  
<div *ng-for="#item of items">

更新:此评论现已过期,请参阅已接受的回答

OK,目前,以下工作

/// <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);
  }
}

我错过了什么

您需要导入For(第3行)

你需要声明你对For组件的依赖(第9行)

"ng-repeat"的正确语法是当前*for="#item of items"

在开发过程中,它似乎已经改变了很多,所以如果它再次改变,我不会感到惊讶。

对于angular 8及以上版本,正确的语法是

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

相关内容

最新更新