在angular2上的自定义管道上扩展管道,如货币或数字

imt*_*tah 11 pipe typescript angular

我想在我的自定义管道上调用numberPipe,我找到了这个答案

Angular2在自定义管道中使用基本管道

但我这个解决方案对我不起作用.我有一个错误"无法找到管道'bigInteger'"

import { Pipe, PipeTransform } from "@angular/core"
import { CurrencyPipe  } from "@angular/common"

@Pipe({
 name: "bigInteger"
 })
 export class BigInteger extends CurrencyPipe implements PipeTransform {
   transform(value: any): string {
    return value
 }
}
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 8

更新

至少在Angular4中应该修复一段时间

原版的

DI和类的已知问题扩展了其他类

https://github.com/angular/angular/issues/8694

使用此功能已修复,您可以使用组合而不是继承:

@Pipe({
  name: "bigInteger"
})
export class BigInteger implements PipeTransform {

  constructor(private currencyPipe:CurrencyPipe) {}

  transform(value: any): string {
     return this.currencyPipe.transform(value);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 除此之外,我在视图模板中使用自定义管道时也遇到错误,抱怨没有CurrencyPipe的提供程序.所以为了解决这个错误,在我的app.module.ts中我将它添加到Providers列表中:`providers:[...,CurrencyPipe]`现在我的基于它的自定义管道工作了!现在,我确信这可能不是最佳做法或其他什么,但我需要看到一些合理的方法来覆盖默认管道或者可能有更好的方法? (3认同)

小智 5

也许已过时,但这对我有用Angular 5):

import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common'

@Pipe({
  name: 'bigInteger'
})
export class BigInteger extends DecimalPipe implements PipeTransform {
  transform(value: any, args?: any): any {

    let result;
    result = super.transform(value, args);

    //any transformations you need

    return result;
  }

}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像常规数字管道一样使用它,但是可以根据需要自定义:

<span>{{someValue | bigInteger : '1.2-2'}}</span>
Run Code Online (Sandbox Code Playgroud)