Angular data 2

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,'第一个商品',['电子产品','硬件产品']),
      new Product(2,'商品2',2.99,4,'第二个商品',['电子产品']),
      new Product(3,'商品3',1.89,5,'第三个商品',['图书']),
      new Product(4,'商品4',1.33,4.5,'第四个商品',['电子产品','硬件产品']),
      new Product(5,'商品5',3.0,2.5,'第五个商品',['硬件产品']),
      new Product(6,'商品6',4.50,1.5,'第六个商品',['电子产品']),
    ];
  }

}


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">
    ![](http://upload-images.jianshu.io/upload_images/8620425-68d8d59b05470d62?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    <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、样式绑定
以星级评价组件为例(用方括号[class.样式名]=“用ngFor循环出来的绑定变量”)

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传递给子组件,�通过在子组件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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容