一.使用的第一个Angular技术
1.模板数据绑定 根据数据数量重复生成
*ngFor="let XXX of YYY"
① 在.component.ts文件中声明数据类型
eg:如stars
a. private stars: boolean[];
b. ngOnInit()中初始化,对数据初始化
c.在html文件中 对咬重复生成的模块 添加*ngFor="let XXX of YYY"
XXX为生成新数组名,YYY为.ts文件中声明的对象
2.数据绑定
①差值表达式
{{}} : 直接引用
②属性绑定
eg:product的图片路径
在product.component.ts文件中
private imgUrl = 'http://placehold.it/320x150';
随后在html中设置<img>为
<img [src]="imgUrl">
即可将图片URL与后台数据绑定
PS:特例.样式绑定.html文件 中
<span *ngFor="let star of stars" class="glyphicon glyphicon-star"
[class.glyphicon-star-empty]="star"></span>
将class中的样式提出,若为真则添加样式,假则不改变样式.
3.父组件数据如何通过子组件传递
在stars.component.ts声明前加上@Input()
<app-stars></app-stars>组件为product的子组件
--------------------------------------------------------------------------------------------
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">
<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.rating"></app-stars>
</div>
</div>
</div>
-----------------------------------
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>;
private imgUrl = 'http://placehold.it/320x150';
constructor() { }
ngOnInit() {
this.products = [
new Product( 1, '"First-Picture"', 1.99, 4.5, '"第一个动漫库图片,我的英雄学院"', ['Anime', 'Hot']),
new Product( 2, '"Seconde-Picture"', 2.99, 3.5, '"第二个动漫库图片,我的英雄学院"', ['Anime', 'Hot']),
new Product( 3, '"Third-Picture"', 3.99, 4.5, '"第三个动漫库图片,我的英雄学院"', ['Anime', 'Hot']),
new Product( 4, '"Forth-Picture"', 4.99, 3.5, '"第四个动漫库图片,我的英雄学院"', ['Anime', 'Hot']),
new Product( 5, '"FIfth-Picture"', 5.99, 2.5, '"第五个动漫库图片,我的英雄学院"', ['Anime', 'Hot']),
new Product( 6, '"Sixth-Picture"', 5.99, 1.5, '"第六个动漫库图片,我的英雄学院"', ['Anime', 'Hot'])
];
}
}
export class Product {
constructor(
public id: number,
public title: string,
public price: number,
public rating: number,
public desc: string,
public categories: Array<string>
) {
}
}
-----------------------------------
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
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-stars',
templateUrl: './stars.component.html',
styleUrls: ['./stars.component.css']
})
export class StarsComponent implements OnInit {
@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);
}
}
}