I recently wrote up an answer to this Stack Overflow question, and I was so proud of it that I decided to write up a blog post about it.
The Problem
the basic gist of the question was that the original poster was using the built-in currency pipe but wanted to show a negative number with parentheses instead of with a minus sign.
The Solution
My solution involves chaining another custom pipe after the currency pipe. Since the currency pipe outputs a string my custom pipe can just do some string manipulation and return a new one with parentheses instead of minus signs.
<h1>{{someNumber | currency:'USD':true | myCustomPipe}}</h1> The Code
Here's the code for the custom pipe:
@Pipe({ name: 'minusSignToParens' }) export class MinusSignToParens implements PipeTransform { transform(value: any, args?: any): any { return value.charAt(0) === '-' ? '(' + value.substring(1, value.length) + ')' : value; }
The logic can be interpreted in plan english like this, "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 then return the entire string without that first character and append a string of a single paren on either side of it".
Here's an example of how you might use this in a component:
@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() {} } The Plunk
I created a plunkr demo for this pipe that acts as a minimum workable example. I like starting from this Angular 2.4.1 plunkr starter. This starter plunk lays out all of the Angular 2 boilerplate for setting up a new project. You can create and import files right there in Plunkr so it feels (sort of) close to "real" development like you would do locally with an IDE. I am not a fan of using Plunkr for too many things, but one thing I think it is really excellent for is creating small demo projects that serve as answers to stack overflow questions (or that go along with questions as well).
The Glory
It can be nice racking up stack overflow reputation points, showing off your Angular 2 knowledge, and flexing problem solving muscles, but I also like to think that I'm helping others and making a positive impact on the world. It felt great seeing the original posters thank you comment on my answer:
Comments
|
AuthorThe posts on this site are written and maintained by Jim Lynch. About Jim...
Categories
All
Archives
April 2018
|