代码之家  ›  专栏  ›  技术社区  ›  shohrukh

角管干燥

  •  2
  • shohrukh  · 技术社区  · 8 年前

    <p>{{amount1 | currency : 'USD' : 'symbol' : '1.0-0'}}</p>
    ...
    <p>{{amount2 | currency : 'USD' : 'symbol' : '1.0-0'}}</p>
    ...
    <div>{{amount3 | currency : 'USD' : 'symbol' : '1.0-0'}}</div>
    ...
    <h1>{{amount4 | currency : 'USD' : 'symbol' : '1.0-0'}}</h1>
    

    在这个例子中如何实现干燥?注意,amount元素不在同一级别(即不能通过*ngFor生成)。

    1 回复  |  直到 8 年前
        1
  •  4
  •   ConnorsFan    8 年前

    你可以延长 CurrencyPipe

    import { Pipe } from '@angular/core';
    import { CurrencyPipe } from '@angular/common';
    
    @Pipe({
      name: 'usdCurrency'
    })
    export class UsdCurrencyPipe extends CurrencyPipe {
      transform(value: number, digitsInfo: string = "1.0-0"): any {
        return super.transform(value, "USD", "symbol", digitsInfo);  }
    }
    

    并在模板中应用该自定义管道:

    <p>{{amount1 | usdCurrency }}</p>
    <p>{{amount2 | usdCurrency }}</p>
    <div>{{amount3 | usdCurrency }}</div>
    <h1>{{amount4 | usdCurrency : "1.2-2" }}</h1>
    

    在上面的例子中, digitsInfo 可用作可选参数。如果需要,可以提供其他参数( currencyCode , display locale ).

    this stackblitz

    推荐文章