ngFor指令用法
1、在product.component.ts 文件中定義如下
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
private products:Array<Product>;
constructor() { }
ngOnInit() {
this.products = [
new Product(1,'商品1',1.99,3.5,'第一個(gè)商品',['電子產(chǎn)品','硬件產(chǎn)品']),
new Product(2,'商品2',2.99,4,'第二個(gè)商品',['電子產(chǎn)品']),
new Product(3,'商品3',1.89,5,'第三個(gè)商品',['圖書']),
new Product(4,'商品4',1.33,4.5,'第四個(gè)商品',['電子產(chǎn)品','硬件產(chǎn)品']),
new Product(5,'商品5',3.0,2.5,'第五個(gè)商品',['硬件產(chǎn)品']),
new Product(6,'商品6',4.50,1.5,'第六個(gè)商品',['電子產(chǎn)品']),
];
}
}
export class Product{
constructor(
public id:number,
public title:string,
public price:number,
public rating:number,
public desc:string,
public categorys:Array<string>
){
}
}
2、在product.component.html模板文件中定義
<div *ngFor="let product of products" class="col-md-4 col-sm-4 col-lg-4">
<div class="thumbnail">

<div class="caption">
<h4 class="pull-right">{{product.price}}元</h4>
<h4><a href="">{{product.title}}</a></h4>
<p>{{product.desc}}</p>
</div>
<div>
<app-stars></app-stars>
</div>
</div>
</div>
屬性綁定和樣式綁定
1、屬性綁定
在component中
private imgUrl = 'http://placehold.it/320x150';
在模板中
<img [src]="imgUrl" alt="">
2、樣式綁定
以星級(jí)評(píng)價(jià)組件為例(用方括號(hào)[class.樣式名]=“用ngFor循環(huán)出來(lái)的綁定變量”)
stars.component.html中代碼示例
<p>
<span *ngFor="let star of stars" class="glyphicon glyphicon-star"
[class.glyphicon-star-empty]="star"></span>
</p>
stars.component.ts中代碼示例
...
private stars:boolean[];
...
constructor() { }
ngOnInit() {
this.stars=[false,false,true,true,true];
...
}
3、輸入綁定(父組件product傳遞給子組件,?通過(guò)在子組件stars的變量上加@Input修飾符)
stars.component.html中代碼示例
<p>
<span *ngFor="let star of stars" class="glyphicon glyphicon-star"
[class.glyphicon-star-empty]="star"></span>
<span>{{rating}}星</span>
</p>
stars.component.ts中代碼示例
...
@Input()
private rating:number = 0;
private stars:boolean[];
constructor() { }
ngOnInit() {
this.stars=[];
for(let i = 1;i<=5;i++){
this.stars.push(i>this.rating);
}
}
...
父組件 product.component.html中代碼示例
<div *ngFor="let product of products" class="col-md-4 col-sm-4 col-lg-4">
<div class="thumbnail">
<img [src]="imgUrl" alt="">
<div class="caption">
<h4 class="pull-right">{{product.price}}元</h4>
<h4><a href="">{{product.title}}</a></h4>
<p>{{product.desc}}</p>
</div>
<div>
<app-stars [rating]="product.rating"></app-stars>
</div>
</div>
</div>