Datz
Datz

Reputation: 3841

Global number formatting in Angular?

At many places in my application I want to format numbers the same. I could do it with

{{decimalValue | number:'3.1-5':'fr'}}

at every single place.

But how can I accomplish this without repeating this line for every number I want to format?

Can I define it somewhere globally? Or should I write my own pipe which knows the proper formatting? I don't want to change hundreds lines of code sometime in the future when the NFR changes...

Upvotes: 1

Views: 542

Answers (1)

maxime1992
maxime1992

Reputation: 23793

If you look at the source code: https://github.com/angular/angular/blob/master/packages/common/src/pipes/number_pipe.ts

You see that you can inject the locale. So provide it with the value of your choice as a provider higher up in the hierarchy of your app and you will be able to remove this param at least (fr)

As for the '3.1-5' param, from what I see you have 2 options:

  • either define this as a string in a shared file and in each of your components, declare a variable that is the same as the global one like public NUMBER_FORMAT = NUMBER_FORMAT when NUMBER_FORMAT would be imported from a shared file and defined as const NUMBER_FORMAT: string = '3.1-5'. Then in the HTML you could do | number:NUMBER_FORMAT
  • Create a new number pipe of your own which extends the original one and where in the transform method you call super.transform('3.1-5', 'fr')

Upvotes: 2

Related Questions