2017-02-10 93 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']; 
}