angular的属性绑定

1. 图片地址属性绑定

html文件

<img [src]="imgUrl">

ts文件

export class ProductComponent implements OnInit {
 //声明图片的url地址
  private imgUrl = 'http://placehold.it/260x150';
  
  constructor() { }

  ngOnInit() {}

}

2. 样式绑定

html文件

//如果star为true则添加glyphicon-star-empty这个类,如果为false则不会添加这个类
<
span *ngFor="let star of stars" class="glyphicon glyphicon-star" [class.glyphicon-star-empty]="star"></span>

ts文件

export class StarsComponent implements OnInit {
  
  private stars:boolean[];

  constructor() { }

  ngOnInit() {
      this.stars=[false,false,false,true,true]
  }

}

3. 输入属性:父组件的属性传递给子组件

子组件html

<span *ngFor="let star of stars" class="glyphicon glyphicon-star" [class.glyphicon-star-empty]="star"></span>
<span>{{rating}}星</span>

子组件ts文件

import { Component, OnInit ,Input } from '@angular/core';
@Component({
  selector: 'app-stars',
  templateUrl: './stars.component.html',
  styleUrls: ['./stars.component.scss']
})
export class StarsComponent implements OnInit {
//input装饰器,星级评价的组件的rating属性应该由他的父组件传递给它
  @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) } } }

父组件html

<div *ngFor="let product of products" class="col-md-4 col-sm-4 col-lg-4">
    <div class="thumbnail">
        <img [src]="imgUrl">
        <div class="caption">
            <h4 class="pull-right">{{product.price}}元</h4>
            <h4><a>{{product.title}}</a></h4>
            <p>{{product.desc}}</p>
        </div>
        <div>
            //输入属性
            <app-stars [rating]="product.star"></app-stars>
        </div>
    </div>
</div>
原文地址:https://www.cnblogs.com/leiting/p/8384196.html