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 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.
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.
Here's the code for the custom pipe:
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:
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).
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:
Your comment will be posted after it is approved.
Leave a Reply.
The posts on this site are written and maintained by Jim Lynch. About Jim...