1. 管道
管道能很好的封裝和共享的通用“值-顯示”轉(zhuǎn)換邏輯寞冯。我們可以像樣式一樣使用它們辟躏,把它們?nèi)拥侥0灞磉_式中,以提升視圖的表現(xiàn)力和可用性撇眯。
2. 內(nèi)置管道(常用)
-
DatePipe
使用:date_expression | date[:format[:timezone[:locale]]]
如:{{nowDate | date='fullDate'}}
更多參數(shù)配置見:DatePipe -
JsonPipe
使用:{{object | json}}
說明:將值轉(zhuǎn)換為json字符串涤躲,與JSON.stringify
效果一樣 -
LowerCasePipe
棺耍、UpperCasePipe
使用:{{ string | lowercase(uppercase)}}
-
TitleCasePipe
使用:{{string | titlecase}}
說明:字符串第一個字母大寫 -
SlicePipe
使用:array_or_string_expression | [slice]):start[:end]
如:{{ string | slice:0:3}}
更多參數(shù)配置見:SlicePipe
3. 自定義管道
- 創(chuàng)建自定義管道
bigPipe.pipe.ts
import { Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'bigPipe'
})
export class BigPipePipe implements PipeTransform {
transform(value: any, args?: any): any {
if (value > 10) {
return '大于10不顯示';
}
return null;
}
}
- 使用管道
- 在組件所屬模塊declarations中導入
declarations: [
AppComponent,
BigPipePipe
],
- 在模板中使用
<p>{{ 20 | bigPipe}}</p>
輸出<p>大于10不顯示</p>
-
注意:
a. 使用@Pipe
裝飾器定義Pipe
的 metadata 信息,如Pipe
的名稱 - 即 name 屬性
b. 實現(xiàn)PipeTransform
接口中定義的transform
s 方法