七、管道

50 阅读1分钟

在Angular中,管道(Pipe)是一种用于在模板中转换数据的功能。它们通常用于格式化数据,比如日期、货币、百分比等。Angular提供了一些内置管道,同时也允许你创建自定义管道。

一 内置管道

  • 在app.module.ts中引入
import {CommonModule} from '@angular/common';
@NgModule({
 declarations: [
 ...
  
 ],
 imports: [
   ...,
    CommonModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
  1. DatePipe:格式化日期。

    html

    {{ value | date:'short' }}
    
  2. UpperCasePipe:将文本转换为大写。

    html

    {{ value | uppercase }}
    
  3. LowerCasePipe:将文本转换为小写。

    html

    {{ value | lowercase }}
    
  4. CurrencyPipe:将数字格式化为货币。

    html

    {{ value | currency:'USD':'symbol' }}
    
  5. PercentPipe:将数字格式化为百分比。

    html

    {{ value | percent }}
    
  6. DecimalPipe:格式化数字。

    html

    {{ value | number:'1.2-2' }}
    
  7. JsonPipe:将对象转换为JSON字符串。

    html

    {{ value | json }}
    
  8. 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
})