1

In a component I have an object as below:

statuses = {
    'accepted' : 'در حال حرکت به سمت مبدا',
    'picking' : 'در حال دریافت مرسوله',
    'delivering' : 'در حال حرکت به سمت مقصد',
    'delivered' : 'در حال تحویل دادن مرسوله'
};

and in the html:

<div *ngFor="let order of orders;">
  <div class="col-md-12 signle-order-div">
    <div class="col-md-4">
      <fa name="motorcycle" rotate="horizontal"></fa>
      <label>{{order.status.last_status}}</label><!-- this gives 'picking' -->
    </div>
  </div>
</div>

How do I print the relevant array index from the statuses object instead of picking?

M Reza Saberi
  • 7,134
  • 9
  • 47
  • 76
  • https://stackoverflow.com/questions/35405618/ngfor-with-index-as-value-in-attribute Like that? – Austin T French Mar 08 '18 at 13:29
  • or do you mean the index as "picking is the second in the list of statuses" ? Because, in this case, your statuses are actually not a list but an object, so it doesn't make sense IMO to talk about index here. you would have to change your structure a bit. – Pac0 Mar 08 '18 at 13:32
  • Ok do i need to change the object to an array of objects? – M Reza Saberi Mar 08 '18 at 13:34
  • Goseo : you can do that. Then you can use the [findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex()) method to get the index of the element. – Pac0 Mar 08 '18 at 13:36
  • or you can change your statuses to a more complex structure like this : `{statuses = { 'accepted' : { label: 'در حال حرکت به سمت مبدا', index: 0}, ... }` (but I would go for your first suggestion if you can, it looks simpler) – Pac0 Mar 08 '18 at 13:37

1 Answers1

0

Your statuses object is not a list, it doesn't make sense as it is to talk about the (numerical) index of the elements.

You can change it to an array : You could change your structure like this (there are other ways, of course) :

statuses = [
    {code: 'accepted', label: 'در حال حرکت به سمت مبدا'},
    {code: 'picking' : label: 'در حال دریافت مرسوله'},
    {code: 'delivering' : label: 'در حال حرکت به سمت مقصد'},
    {code: 'delivered' : label: 'در حال تحویل دادن مرسوله'},
]

then to get the index :

// get the index of a specific order.status.last_status
statuses.findIndex(status => status.code === order.status.last_status)

I would recommend you to calculate the index as a additional field of your order object, in your component code, as I prefer not to have complex function directly in the template {{ ... }}. But it should work in the template anyway.

Pac0
  • 21,465
  • 8
  • 65
  • 74