碎碎念:知识点梳理归纳,如果有什么不对的感谢大家指正一起学习!
管道:处理原始值到显示值的一个转换
一、angular内置管道
(列举几个常用的)
- date:格式化日期
- uppercase:转大写
- lowercase:转小写
- number:整数和小数格式化
二、示例
- date管道
例1:管道前
// ts
birthday: Date = new Date();
例2:管道后(在html数据上处理)
一般写法
date加参数写法
- number 管道
转换前:
// html
<p>数字格式化:{{pi }}</p>
// ts
pi: number = 3.14159265;
转换后:
参数格式: 整数部分保留位数 . 小数部分保留最小位数 - 小数部分保留最大的位数
(默认值:1).(默认值:0)- (默认值:3)
<p>数字格式化:{{pi | number:'2.1-2' }}</p>
整数部分保留2位,小数部分保留了两位,不够0补上
二、自定义管道
- 例1,将当前的值与传入的参数值做一个乘法处理
// 创建 multiple 管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'multiple'
})
export class MultiplePipe implements PipeTransform {
transform(value: any, args?: any): any {
if (!args) {
args = 1;
}
return value * args;
}
}
// html
<p>数字:{{test | multiple }}</p>
// ts
test: number = 3;
在declarations中声明
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule
],
declarations: [ProductComponent,MultiplePipe],
exports:[ProductComponent]
})
export class ProductModule { }
因为没有传入第二个参数,所以默认为1,最后结果为3
例2.传入第二个参数
<p>数字:{{test | multiple:"2" }}</p>
3*2 最后结果为6
- 例2:使用管道将服务器返回的英文转换为中文
在ts定义三个英文属性值
// ts
male: string = 'male';
female: string = 'female';
undefined: string = 'abc';
在页面上绑定并添加管道
// html
<p>男生:{{male | sexTransform}} </p>
<p>女生:{{female | sexTransform }}</p>
<p>未知:{{undefined | sexTransform }}</p>
管道
// pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sexTransform'
})
export class SexTransformPipe implements PipeTransform {
transform(value: string): string {
switch (value) {
case 'male': return '男';
case 'female': return '女';
default: return '未知';
}
}
}
三、 其他概念
4. 链式管道:
( 一个模板表达式可以连续使用多个管道进行不同的处理。)
5. 在declarations数组中添加自定义管道就可以像内置管道使用
6. 在transform方法中,第一个参数为需要被转换的值,后面有若干个可转换的参数,该方法需要返回一个转换后的值