2017-02-10 109 views
0

我想實現一個基本的購物清單,但我的ngFor Angular無法正常工作。Angular2 ngFor不工作

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

 

 
@Component({ 
 
    selector: 'my-app' 
 
}) 
 
@View({ 
 
    template: '<h1>{{title}}</h1><ul><li *ngFor="let i of items"><span>{{i}}</span></li></ul>' 
 

 
}) 
 
export default class MyAppComponent { 
 
    title = 'ShoppinList'; 
 
    items = ['Milk','Ham','Eggs']; 
 
}

出現是唯一 「載入中...」,我得到超過10個神祕的錯誤。

enter image description here

+1

您的組件應該包含'模板'和@'View'可以被刪除。你的'import'語句不正確。也許你是從一箇舊的測試版本複製/粘貼? – Igor

回答

0

你不必在這裏使用@View

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     {{title}} 
     <ul><li *ngFor="let i of items"><span>{{i}}</span></li></ul> 
    </div> 
    `, 
}) 

export class App { 
    title = 'ShoppinList'; 
    items = ['Milk','Ham','Eggs']; 
} 

Working plunker

2

沒有試圖首先我在上面注意到了import語句錯誤。應該是:

import { Component } from '@angular/core' 
1

@View()在一年前被刪除。如果您看到使用它的示例,請將內容移至@Component()修飾器,而directivespipes已從@Component()移至@NgModule() s declaration

你必須要使用ngFor每個模塊中添加CommonModule@NgModule({ imports: [CommonModule], ...}) export class SomeModule{}(或角shippled其他指令 - BrowserModule已經包含CommonModule)。

1

它是使用ngIf和在你的組件屬性中使用你的模板的好方法。

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


@Component({ 
    selector: 'my-app', 
    template : '<div> 
     <h1>{{title}}</h1> 
     <ul *ngIf="items"> 
      <li *ngFor="let i of items"><span>{{i}}</span></li> 
     </ul> 
    </div>' 
}) 

export default class MyAppComponent { 
    title : string = 'ShoppinList'; 
    items : Array<string> = ['Milk','Ham','Eggs']; 
}