0
votes

I am trying to build a customise angular pipe. This pipe would be similar to Decimal Pipe.

I am rendering multiple items on the screen. Each items has it's own price and each item has different decimals places and which comes from database dynamically. I can use decimal pipe but I have to specify decimals place individually for each item. So basically what I am trying to do is, create a customise pipe that converts value(price) to its own decimals places instead of me specifying decimals places for each item.

I am using two objects(item and decimalplaces) which I have specified below.

'item': {
'itemID': 'id',
'name:' 'itemName'
'feature': 'feature'
'price': 200
}
'decimalPlace': {
'decimals': 2
'itemID': 'id'
}

Currently what I am trying to do is that I am calling getDecimals method(which returns decimalsPlaces object) in pipe constructor then I am specifying item name using string interpolation. Example:

{{ item.price | customisedPipe: {{ item.itemId }} }}

Inside the pipe class I am using find() function to compare 'item.itemId' and decimalPlace.decimals if its match then I am transforming value to return decimal places value.

This way it works, but I have been told not use this way. So, I'll appreciate if someone can suggest any other solution.

Please let me know if this question doesn't make sense.

1
The format of parameter to the pipe is wrong. should be customisedPipe: 'item.itemId' but otherwise nothing wrong with what you showed. But the explanation of what you did in the pipe code is confusing (at least to me). maybe put that code in the question. Or maybe it will be a different question!Felix

1 Answers

1
votes

A pipe is meant to work with it's parameters only, and no external data. I think that you should bundle your 'decimalPlace' objects into your item objects, and then simply send the items through the pipe.

That way, the pipe will have, for each object passed in, all of the item's info, including the price and the number of decimal places, and will not have to do any sort of "find" operation.