[英]Angular 2 *ngFor not working
以下是我的组件:
import { Component } from 'angular2/core';
@Component({
selector: 'test',
template:
`
<ul >
<li *ngFor="let t of test">
<span >{{t}}</span>
</li>
</ul>
`
})
export class TestComponent implements OnInit{
test: string[];
constructor(){
this.test = ["Saab", "Volvo", "BMW"];
}
}
尝试加载组件时出现以下错误:
EXCEPTION: Template parse errors:
Can't bind to 'ngFor' since it isn't a known native property ("<ul >
<li [ERROR ->]*ngFor="let t of test">
<span >{{t}}</span>
</li>
"):
另外,我不确定在导入 Component 时是否应该使用“@angular/core”或“angular2/core”。
出现此问题的原因可能是您尚未将公共模块导入到您当前使用的模块中。
尝试导入
import { CommonModule } from "@angular/common";
进入您当前的模块,看看问题是否已解决。
公共模块添加了来自 angular 2 的所有内置指令。
请参阅 angular.io 的 commonModule 文档
希望有帮助:)
我遇到了同样的问题,经过大量搜索和测试后,我才发现我忘记在模块的“声明”中声明我的组件。
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { SearchComponent } from './search.component'; @NgModule({ imports: [ CommonModule, RouterModule.forChild([ { path: '', component: SearchComponent }, ]) ], exports:[ ], declarations: [ SearchComponent ], }) export class SearchModule { }
你的模板应该是:
<ul>
<li *ngFor="#t of test">
<span >{{t}}</span>
</li>
</ul>
或者在较新版本中以这种方式:
<ul>
<li *ngFor="let t of test">
<span>{{t}}</span>
</li>
</ul>
我经历过类似的行为。 问题是我在 HTML 中包含了 Angular 2 的最小化版本。
如果是这样,请尝试包含 Angular 的未最小化文件
使用 Let 为我解决了这个问题
<ul> <li *ngFor = "let test of testArray">{{test}}</li> </ul>
对我来说,问题是我使用带有 HTML 加载器的 Webpack,它在 Angular 编译之前最小化了 HTML,从而从ngFor
删除了*
。
{
test: /\.html$/,
use: [ {
loader: 'html-loader',
options: {
//minimize: true, // Make sure that you are not minimizing when using Angular
removeComments: false,
collapseWhitespace: false
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.