Custom Pipes

Angular allows you to create your own custom pipes:

  1. import { Pipe, PipeTransform } from '@angular/core';
  2. const FILE_SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  3. const FILE_SIZE_UNITS_LONG = ['Bytes', 'Kilobytes', 'Megabytes', 'Gigabytes', 'Pettabytes', 'Exabytes', 'Zettabytes', 'Yottabytes'];
  4. @Pipe({
  5. name: 'formatFileSize'
  6. })
  7. export class FormatFileSizePipe implements PipeTransform {
  8. transform(sizeInBytes: number, longForm: boolean): string {
  9. const units = longForm
  10. ? FILE_SIZE_UNITS_LONG
  11. : FILE_SIZE_UNITS;
  12. let power = Math.round(Math.log(sizeInBytes) / Math.log(1024));
  13. power = Math.min(power, units.length - 1);
  14. const size = sizeInBytes / Math.pow(1024, power); // size in new units
  15. const formattedSize = Math.round(size * 100) / 100; // keep up to 2 decimals
  16. const unit = units[power];
  17. return `${formattedSize} ${unit}`;
  18. }
  19. }

Each custom pipe implementation must:

  • have the @Pipe decorator with pipe metadata that has a name property. This value will be used tocall this pipe in template expressions. It must be a valid JavaScript identifier.
  • implement the PipeTransform interface's transform method. This method takes the value being pipedand a variable number of arguments of any type and return a transformed ("piped") value.
    Each colon-delimited parameter in the template maps to one method argument in the same order.
  1. import { Component } from '@angular/core';
  2. @Component({
  3. selector: 'app-root',
  4. template: `
  5. <div>
  6. <p *ngFor="let f of fileSizes">{{ f | formatFileSize }}</p>
  7. <p>{{ largeFileSize | formatFileSize:true }}</p>
  8. </div>`
  9. })
  10. export class AppComponent {
  11. fileSizes = [10, 100, 1000, 10000, 100000, 10000000, 10000000000];
  12. largeFileSize = Math.pow(10, 15)
  13. }

View Example

原文: https://angular-2-training-book.rangle.io/handout/pipes/custom_pipes.html