在Angular中,管道(Pipe)是一种用于在模板中转换数据的功能。它们通常用于格式化数据,比如日期、货币、百分比等。Angular提供了一些内置管道,同时也允许你创建自定义管道。
一 内置管道
- 在app.module.ts中引入
import {CommonModule} from '@angular/common';
@NgModule({
declarations: [
...
],
imports: [
...,
CommonModule
],
providers: [],
bootstrap: [AppComponent]
})
-
DatePipe:格式化日期。
html
{{ value | date:'short' }} -
UpperCasePipe:将文本转换为大写。
html
{{ value | uppercase }} -
LowerCasePipe:将文本转换为小写。
html
{{ value | lowercase }} -
CurrencyPipe:将数字格式化为货币。
html
{{ value | currency:'USD':'symbol' }} -
PercentPipe:将数字格式化为百分比。
html
{{ value | percent }} -
DecimalPipe:格式化数字。
html
{{ value | number:'1.2-2' }} -
JsonPipe:将对象转换为JSON字符串。
html
{{ value | json }} -
SlicePipe:从数组或字符串中截取一部分。
html
{{ value | slice:start:end }}
二、 链式管道
html
{{ value | pipe1 | pipe2 }}
三、自定义管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myCustomPipe'
})
export class MyCustomPipe implements PipeTransform {
transform(value: string, prefix: string): string {
if (!value) return value;
return prefix + value.toUpperCase();
}
}
四、 管道的纯性(Purity)
- 通过pure可以控制管道的纯性:
默认情况下,管道是纯的。纯管道只有在输入值发生变化时才会执行转换,这有助于提高性能。而不纯管道会在每个变更检测周期中都执行,即使输入值没有变化,这可能会影响性能。
@Pipe({
name: 'myImpurePipe',
pure: false
})