angular--常见管道
2018-01-07 本文已影响0人
林ze宏
- 日期格式转换(date)
- 数字(number)
- 大小写转换(uppercase、lowercase)
- 自定义管道(ng g pipe pipefile/mulit)
app.module.ts:
import { MultiPipe } from './pipe/multi.pipe';
declarations: [
AppComponent,
TestDemoComponent,
MultiPipe
],
HTML界面:
<div>
<p>日期:{{birthday | date: 'yyyy-MM-dd HH:mm:ss'}}</p>
<p>数字:{{3.12645 | number:'2.1-4'}}</p> '2.1-4'表示整数2位,小数最少1位,最多4位
<p>大写转小写:{{'TEST' | lowercase}}</p>
<p>大写转小写:{{'test' | uppercase}}</p>
<p>自定义管道;{{ 4 | multi}}</p>
<p>自定义管道;{{ 4 | multi: 5}}</p>
</div>
ts:
public birthday: Data = new Date();
image.png
例子:自定义管道
filter管道:ng g pipe pipe/filter
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(list: any[], field: string, keyword: string): any {
if (!field || !keyword) {
return list;
}
return list.filter(
item => {
let val = item[field];
return val.indexOf(keyword) >= 0;
}
);
}
}
界面:
<div class="col-md-4 col-sm-4 col-lg-4" *ngFor="let product of products | filter:'title':keyWord ">
<div class="thumbnail" >
<img src="http://placehold.it/320*150" class="productimg" alt="">
<div class="caption">
<h4 class="pull-right">{{product.price}}</h4>
<h4 class=""><a [routerLink]="['/product', product.id]">{{product.title}}</a></h4>
<p>{{product.desc}}</p>
</div>
<div>
<app-stars [rating]="product.rating"></app-stars>
</div>
</div>
</div>