什么是pipe
中文释义“管道”。
把数据作为输入,然后转换它,给出期望的输出。例如,将UTC时间转为指定格式;中英文的转化;大小写的转化;等等。
pipe 的使用
<p>
{{'HELLO-WORLD WORKS!' | lowCase}}
</p>
链式pipe
<p>
{{'HELLO-WORLD WORKS!' | lowCase | upperCase}}
</p>
自定义 pipe
-
创建pipe命令:
ng generate pipe pipe-name
-
写实现
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'lowCase'
})
export class LowCasePipe implements PipeTransform {
transform(value: any): any {
return value.toLowerCase();
}
}
- 使用 pipe
<p>
{{'HELLO-WORLD WORKS!' | lowCase}}
</p>
附录
-
Angular 内置了一些管道
DatePipe
UpperCasePipe
LowerCasePipe
CurrencyPipe
PercentPipe
- ...
-
@pipe
这个注解里有两个参数,即:
@Pipe({
name: string
pure?: boolean
})
其中name就是该pipe的名字,而pure表示该pipe是纯pipe还是非纯pipe。
- 纯pipe:只有在它检测到输入值发生了纯变更时才会执行
- 非纯pipe:在每个组件的变更检测周期中执行
自定义pipe默认都是非纯pipe。
网友评论