我是角度4的新手。我有两个组件分开app.components:home.component和product.component。我在app.component.ts中初始化了产品的数组元素。我想通过使用* ngFor在home.component.html上显示产品列表。它不会渲染我在home.component.html中设置的位置,但只有我调用它才会渲染。问题出在哪儿 ?
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { DetailsComponent } from './details/details.component';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations: [
AppComponent,
ProductComponent,
DetailsComponent,
HomeComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot([
{
path: '',
pathMatch: 'full',
component: HomeComponent
},
{
path: 'product',
component: ProductComponent
},
{
path: 'details',
component: DetailsComponent
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
products = [{
titre:"titre1",
desc:"desc1"
},{
titre:"titre2",
desc:"desc2"
},{
titre:"titre3",
desc:"desc3"
}];
}
app.component.html
<router-outlet></router-outlet>
product.component.ts
import {Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
@Input() titre:string;
@Input() description:string;
constructor() { }
ngOnInit() {
}
}
product.component.html
<div>
<h5>{{titre}}</h5>
<p class="card-text">{{desc}}</p>
</div>
home.component.html
<div class="home">
<div class="album text-muted">
<div class="container">
<div class="row">
<product
class="col-md-4"
*ngFor="let p of products"
[description]="p.desc"
[titre]="p.titre">
</product>
<!--<product></product>-->
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
你的home.component.ts中是否定义了products
?
HomeComponent应如下所示:
export class HomeComponent{
products = [{
titre:"titre1",
desc:"desc1"
},{
titre:"titre2",
desc:"desc2"
},{
titre:"titre3",
desc:"desc3"
}];
}