Display negative currency with parentheses in Angular 2 / Typescript

Angular The localization of en-us has been updated from 1.3 to display negative currency with a negative sign instead of parentheses. I am using AngularJS 2 / Typescript and would like to override the default negative sign with parentheses (or even something else).

The discussion on this shows the redefinition of negPre and negSuf, however I do not see how to do this with Angular2. Or maybe a more elegant way to achieve this.

+6
source share
1 answer

I appreciate you asking this great question. Of course, a currency pipe exists, but after scanning the current documentation for pipes, it seems that out of the box this pipe will not do what you want, However, you can perform your task using a custom pipe.

1. First, acknowledge that you can “hook pipes.”

For example, you can have a variable like a number, send it through a currency channel and then send it through your own channel:

<h1>{{someNumber | currency:'USD':true | myCustomPipe}}</h1> 

2. Recognize that the currency pipe returns a string.

This means that your custom channel can accept a string, do some string manipulation, and return a new string.

3. Recognize that the string manipulation algorithm to move from the minus sign to parentheses is actually not that difficult.

The logic can be interpreted in terms of english as follows: "If the first character of my input value is not a minus sign, then just return the value, but if it is a minus sign, return the entire line without this first character and add a line from one partner on either side of her. " Using the ternary JavaScript operator might look like this:

 value.charAt(0) === '-' ? '(' + value.substring(1, value.length) + ')' : value; 

I also created a nice tube that makes this at least a feasible example. Suppose you have this component that displays a variable someNumber whose value is -5 (a negative value of 5).

 @Component({ selector: 'my-app', template: ` <h2>MinusSignToParens Pipe Demo</h2> <h1>{{someNumber | currency:'USD':true | minusSignToParens}}</h1> ` }) export class App implements OnInit { private someNumber:any = -5; constructor() {} ngOnInit() {} } 

And here is the code for minusSignToParens:

 @Pipe({ name: 'minusSignToParens' }) export class MinusSignToParens implements PipeTransform { transform(value: any, args?: any): any { return value.charAt(0) === '-' ? '(' + value.substring(1, value.length) + ')' : value; } 

Here is an example in Plunkr if you want to play with it.

And remember what Migos would say, plug it in!

+8
source

Source: https://habr.com/ru/post/1013948/


All Articles