2017-02-10 15 views
0

私は基本的なショッピングリストを実装しようとしていますが、AngularのngForは機能しません。Angular2 ngFor not working

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

あなたのコンポーネントには 'template'が含まれ、@' 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 { Component } from '@angular/core' 
1

@View()はほぼ一年前に削除されました。使用例が表示されている場合は、とpipes@Component()からに移動して、コンテンツを@Component()デコレータに移動してください。

あなたがngFor使用するすべてのモジュールに@NgModule({ imports: [CommonModule], ...}) export class SomeModule{}CommonModuleを追加する必要があります(角度でshippledまたは他のディレクティブを - すでにCommonModuleが含まBrowserModule)。

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']; 
}