2

it seems quite simple but some how i can't loop through the items as i would like to

i have this json object

"meters":{  
      "Rozvadec M11":{  
         "0":{  
            "Name":"m11-mcu13_sm114",
            "Title":"Svarovaci centrum Flexarc",
            "Parent":"m11-mcu13",
            "Status":"Running",
            "State":false
         },
         "1":{  
            "Name":"m11-mcu13_sm115",
            "Title":"Brousici centrum Solicad",
            "Parent":"m11-mcu13",
            "Status":"Running",
            "State":false
         }
      },
      "Rozvadec R1-L":{  
         "0":{  
            "Name":"r1-l-mcu1_sm100",
            "Title":"Amada NCT1",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         },
         "1":{  
            "Name":"r1-l-mcu1_sm101",
            "Title":"Amada 1",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         },
         "2":{  
            "Name":"r1-l-mcu1_sm102",
            "Title":"Amada 2",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         }
      },

what i am trying to do is to loop through all meters to have a list of

"Rozvadec M11"
"Rozvadec R1-L"

and under each have a list of different smartmeters names

i have this in ts

let list =  this.http.get('EndpointURL');
         list.subscribe (
           (response: Response)=> 
           {this.meters.push(response);
           console.log(this.meters);
         })

and this in html (i was trying to loop only through the meters first before i nest the for loops)

<ul *ngFor="let meter of meters">
    <li>{{ meter}}</li>
</ul>
Lamis Abouzina
  • 369
  • 1
  • 3
  • 16

1 Answers1

3

You have most of your code right but the ngFor is not used in that way. The html tag with the ngFor is what will be repeated and you that's why you should use it in the li instead of the list tag ul. It would be like this for you:

<ul>
    <li *ngFor="let meter of meters">
        {{meter}}
    </li>
<ul>

This exact example is covered here in the docs.

EDIT: If you want to access the key of your list, in this SO answer you can see the new way in Angular6 to retrieve it. It will end up like this for your example:

<ul>
    <li *ngFor="let meter of meters | keyvalue">
        {{meter.key}}
    </li>
<ul>

You can read more about the keyValuePipe in the docs.

AntonioGarcía
  • 1,140
  • 2
  • 15
  • 25
  • when i try that it gives me ([object Object]) in the html output ! that's why i am confused ! – Lamis Abouzina Oct 30 '18 at 11:42
  • 1
    Yeah that sounds right. You can either access some data inside your object with: `{{ meter.0.name }}` or you can print the object with the JSON pipe: `{{meter | json}}`. – AntonioGarcía Oct 30 '18 at 11:44