[英]Angular2 ngFor not working
I am trying to implement a basic shopping list, but my ngFor in Angular is not working. 我正在尝试实现基本的购物清单,但是我在Angular中的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']; }
The only thing that appears is "loading..." and I am getting more than 10 cryptic errors. 出现的唯一一件事是“正在加载...”,并且我收到了10多个隐式错误。
Without trying it first I noticed an error in the import statement at the top. 没有先尝试,我注意到顶部的import语句中有一个错误。 Should be:
应该:
import { Component } from '@angular/core'
@View()
was removed almost a year ago. @View()
大约一年前被删除。 If you see examples that use it, just move the content to the @Component()
decorator while directives
and pipes
were moved from @Component()
to @NgModule()
s declaration
. 如果您看到使用它的示例,则在将
directives
和pipes
从@Component()
移至@NgModule()
declaration
同时,将内容移至@Component()
装饰器。
You need to add CommonModule
to @NgModule({ imports: [CommonModule], ...}) export class SomeModule{}
in every module where you want to use ngFor
(or other directives shippled with Angular - BrowserModule
already includes CommonModule
). 您需要添加
CommonModule
到@NgModule({ imports: [CommonModule], ...}) export class SomeModule{}
您要使用的每个模块中ngFor
(或其他指令与角shippled - BrowserModule
已经包含CommonModule
)。
its good way to use ngIf and use your template inside your component properties. 这是使用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'];
}
You don't have to use @View
here. 您不必在这里使用
@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'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.