过滤器(Filter)
Filter:过滤器,用于在view中呈现数据时显示为另一种格式;过滤器的本质一个函数,接收原始数据转换为新的格式进行输出:
function(oldVal){处理 return newVal}
使用过滤器:{{e.salary | 过滤器名}}
Angular2.x 中,过滤器更名为 “管道(Pipe)”
自定义管道的步骤
- 创建管道class,实现转换功能
// sex.pipe.ts 文件
import { Pipe } from "@angular/core";
@Pipe({
name: 'sex' // 过滤器名/管道名
})
export class SexPipe {
// 管道中执行过滤任务的是一个固定的函数
transform(oldVal:number, lang = 'zh'){ // 转换/变形
if(lang === 'zh'){
if(oldVal === 1){
return '男'
}else if(oldVal === 0){
return '女'
}else{
return '未知'
}
}else if(lang === 'en'){
if(oldVal === 1){
return 'Male'
}else if(oldVal === 0){
return 'Female'
}else{
return 'Unknown'
}
}else{
return
}
}
}
- 在模块中注册管道
// app.module.ts
declarations:[SexPipe]
- 在模板视图中使用管道
// html
<td>{{e.sex | sex : 'zh'}}</td>
创建管道(过滤器)的快捷方式
ng g pipe 管道名(过滤器名)
预定义管道
- lowercase: 转换小写
{{ename | lowercase}}
- uppercase: 转换大写
{{ename | uppercase}}
- titlecase: 转换首字母大写
{{ename | titlecase}}
- json: 把js对象序列化为JSON对象
{{ename | json}}
···