2016-03-07 47 views
0

我在写一个角度为2的应用程序。在快速入门教程中,所有的东西都可以正常工作,但在我的待办应用程序中,它无法正常工作。* ng-for在角度2 todo应用程序中不起作用

app.component.ts

import {Component, Template, View, NgFor, bootstrap, CORE_DIRECTIVES, FORM_DIRECTIVES} from 'angular2/angular2'; 

@Component({ 
    selector: 'todo-app', 
}) 

@View({ 
    directives : [NgFor, CORE_DIRECTIVES, FORM_DIRECTIVES] 
}) 

@Template({ 
    url: 'components/todo-app/todo-app.html' 
}) 

class TodoAppComponent { 
    todos : Array; 
    constructor() { 
    this.todos = []; 

    TodoFactory.getAll().then((data) =>{ 
     this.todos = data; // I got JSON in todos object. 
    }); 
    } 
} 

待办事项-APP-HTML

<div *ng-for='#todo of todos'> 
    {{ todo.text }} 
</div> 

在我的模板,*ng-for不工作。即使我尝试{{ todos }},它也会显示所有的数据。我搜查了很多,发现我应该将NgFor核心指令传递给directives : [NgFor]这样的模板。这也行不通。任何单一的帮助,将不胜感激。

+1

无需为供应商添加'NgFor','CORE_DIRECTIVES','FORM_DIRECTIVES',它们是默认提供的。 –

+0

你得到的错误信息是什么? –

+0

我在控制台中没有收到任何错误。它清澈透明。 – Vineet

回答

2

你应该的*ng-for*ngFor代替:

<div *ngFor="#todo of todos"> 
    {{ todo.text }} 
</div> 

否则,你不需要anyore指定NgFor,核心和形式的指令......

编辑

也许你在Angular2的上下文之外加载你的数据。在这种情况下,你可以尝试以利用NgZone类,如下所述:

class TodoAppComponent { 
    todos : Array; 
    constructor(private ngZone:NgZone) { 
    this.todos = []; 

    TodoFactory.getAll().then((data) =>{ 
     this.ngZone.run(() => { 
     this.todos = data; // I got JSON in todos object. 
     }); 
    }); 
    } 
} 

有关详细信息,请参阅本plunkr:https://plnkr.co/edit/KKj1br?p=preview

+0

是的,我已经尝试过相同的,但不幸的是没有工作。我也没有任何控制台错误。 – Vineet

+0

你如何加载你的数据? –

+0

我正在从工厂加载数据,即'TodoFactory'。 – Vineet

0

你使用哪种版本Agular2的????

为最新版本,你可以尝试这个,

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

他们改变,

import {Component,View,bind} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser'; 
import {FORM_DIRECTIVES,CORE_DIRECTIVES,FormBuilder, Validators } from 'angular2/common'; // CORE_DIRECTIVES contains all common required API 

然后,

<div *ngFor="#todo of todos"> 
    {{ todo.text }} 
</div> 
0

角度队除去EV ( - )来自beta版本中的模板指令。

因此:

NG-的,NG-模型,纳克级,...

现在:

ngFor,ngModel,ngClass,...

时使用angular2.0.0-beta。0多

0

在RC版本角2角的团队已取消从模板化内部* ngFor语法和改变* NG-的* ngFor,使用代替

以前,你用

<div *ng-for='#todo of todos'> 
    {{ todo.text }} 
</div> 

您应该使用

<div *ngFor='let todo of todos'> 
    {{ todo.text }} 
</div>