我的app.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { routing, appRoutingProviders} from './app.routing'
import { ProductSearchModule} from './productSearch/productSearch.module'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
ProductSearchModule
],
providers: [appRoutingProviders],
bootstrap: [AppComponent]
})
export class AppModule { }
我的productSearch.module
import {NgModule} from '@angular/core'
import {ProductSearchComponent} from './productSearch.component'
@NgModule({
exports: [ProductSearchComponent],
declarations: [ProductSearchComponent],
})
export class ProductSearchModule{}
我的productSearch组件
import { Component, Output } from '@angular/core'
import { Product} from '../shared/product'
@Component({
selector: 'product-search',
templateUrl: 'productSearch.component.html',
styleUrls: ['productSearch.component.css'],
})
export class ProductSearchComponent{
/**
*
*/
constructor() {
var p1 = new Product;
p1.name = "alkan";
var p2 = new Product;
p2.name = "alper";
this.Products = [p1, p2];
}
Products: Product[]
search(){
}
}
productSearch.component.html文件
<li *ngFor="let item for Products">{{item.name}}</li>
如您所见,这是Angular的一个非常基本的例子。我只想打印每种产品的名称。
错误我得到了:
无法绑定到&#39; ngForFor&#39;因为它不是&#39; li&#39;
的已知属性
更新
组件构造函数更改为
var p1 = new Product();
p1.name = "alkan";
var p2 = new Product();
p2.name = "alper";
this.Products = [p1, p2];
和模板html更改为
<li *ngFor="let item of Products">{{item.name}}</li>
但我仍然得到错误:
Can't bind to 'ngForOf' since it isn't a known property of 'li'
答案 0 :(得分:24)
我认为let item of Products
文件中for
不是productSearch.component.html
。
查看documentation
答案 1 :(得分:17)
var p1 = new Product(); //<----added ();
p1.name = "alkan";
var p2 = new Product(); //<----added ();
p2.name = "alper";
this.Products = [p1, p2];
//<---replace for keyword by of keyword
<li *ngFor="let item of Products">{{item.name}}</li>
<强>更新强>
您还需要添加 CommonModule ,如下所示,
import {NgModule} from '@angular/core';
import {ProductSearchComponent} from './productSearch.component'
import {CommonModule} from '@angular/common';
@NgModule({
imports: [CommonModule], //<====added
exports: [ProductSearchComponent],
declarations: [ProductSearchComponent],
})
答案 2 :(得分:0)
*ngFor
是一个驻留在Angular的CommonModule
(来自@angular/common
包)的指令。因此,请确保在您自己的模块中导入此模块,如下所示:
import { CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule, ...],
exports: [...],
declarations: [...],
});
我喜欢做的是创建一个共享模块,它导入所有基本模块,如CommonModule等,然后重新导出它们。因此,当您导入共享模块时,您已经拥有了所有基本指令。