2016-03-07 48 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>