Search code examples
angularpipeangular7angular-pipe

How to use DecimalPipe from component in angular?


I have a requirement that I have to convert the number using the decimal pipe from ts

Instead of use decimal pipe like this

<td>{{rmanFmvRulesDef.max  | number :'1.2-2'}}</td>

I want to manipulate it from the component, can anyone please help me?


Solution

  • As usual in angular you can rely on DI. You can override the transform function in the ts.

    import { DecimalPipe } from '@angular/common';
    
    class MyService {
      constructor(private _decimalPipe: DecimalPipe) {}
    
      transformDecimal(num) {
        return this._decimalPipe.transform(num, '1.2-2');
      }
    }
    

    Add DecimalPipe in the providers Array otherwise it will give an error

    providers: [DecimalPipe,...]