0

Lets say I have a service that returns a list ob objects.

[
  {item: 'box', price: 10, state: 'N'},
  {item: 'toy', price: 15, state: 'U'},
  {item: 'ink', price: 20: state: 'O'}
]

In the webapp I like to map the state to readable text. I would put a map in my component and use it in the template.

Component

map = new Map ([
 [ "N", "new in stock" ],
 [ "U", "used but ok" ],
 [ "O", "out of stock" ]
]);

Template

<tr *ngFor="let d of data">
    <td>{{ d.item }}</td>
    <td>{{ map.get (d.state) }}</td>
</tr>

I am not sure thats the best strategy to do that. It is simple and easy but I would favor a way that is more related to the template (the view) instead of the component (the control).

I can think of a pipe that translates but maybe thats a overkill for that simple problem.

Thanks for suggestions and comments.

3
  • 2
    A pipe is perfectly appropriate for formatting data ("N", "U") into something else ("new in stock", etc.). And it's extremely easy to create, so I wouldn't call it "overkill". Commented Jul 12, 2019 at 8:50
  • Just first process your array in the component into the structure you need in the templae (i.e., do the mapping) and then use that data for the display. Commented Jul 12, 2019 at 8:58
  • To implement the pipe I would have to do the same think with the map inside the pipe. I agree it would be perfect if there is a bit more of logic in the transformation instead of a simple mapping. Commented Jul 12, 2019 at 9:23

1 Answer 1

1

You can create a simple object like this:

TS:

  map = {
    N: "new in stock",
    U: "used but ok",
    O: "out of stock"
  }

HTML:

<tr *ngFor="let d of data">
    <td>{{ d.item }}</td>
    <td>{{ map[d.state] }}</td>
</tr>

or create a simple function with a switch case that would return the full text.

Try like this:

HTML:

<tr *ngFor="let d of data">
    <td>{{ d.item }}</td>
    <td>{{ getFullText(d.state) }}</td>
</tr>

TS:

  getFullText(abb:string) {
    switch(abb) {
      case "N":
      return "new in stock";

      case "U":
      return "used but ok";

      case "O":
      return "out of stock";
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

With the second approach, code needs to be modified if a new item is added in source/destination array!
Thats more or less the same approach I had already in the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.