[英]Angular2 ngFor 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']; }
出现的唯一一件事是“正在加载...”,并且我收到了10多个隐式错误。
没有先尝试,我注意到顶部的import语句中有一个错误。 应该:
import { Component } from '@angular/core'
@View()
大约一年前被删除。 如果您看到使用它的示例,则在将directives
和pipes
从@Component()
移至@NgModule()
declaration
同时,将内容移至@Component()
装饰器。
您需要添加CommonModule
到@NgModule({ imports: [CommonModule], ...}) export class SomeModule{}
您要使用的每个模块中ngFor
(或其他指令与角shippled - BrowserModule
已经包含CommonModule
)。
这是使用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'];
}
您不必在这里使用@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.