Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular html, how to ngfor loop for nested object?

I have an object in our server that is like this;

{
    "NBA": {
        "link": "https://www.nba.com/",
        "ticketPrice": 50
    },
    "UEFA": {
        "link": "https://www.uefa.com/",
        "ticketPrice": 39
    },
    "CL": {
        "link": "https://www.uefa.com/uefachampionsleague/",
        "ticketPrice": 76
    },
    "EuroLeague": {
        "link": "https://www.euroleague.net/",
        "ticketPrice": 42
    }
}

I subscribe this object with this piece of code;

sportsObject : Sports[] //THIS IS THE MEMBER THAT SHOULD BE FILLED WITH THE JSON OBJECT GIVEN
object = Object;
ngOnInit(){
    this.SportsService.getPrices().subscribe(data=>{
      this.sportsObject = data;
    })    
}

And here is my html code;

   <div *ngFor="let key of Object.keys(sportsObject)">
       <p>The {{key}} is {{{{sportsObject[key]}}</p>
   </div>

But I get the "Cannot find a differ supporting object '[object Object]' of type 'object'." error. How can I properly iterate this JSON object?

like image 238
Baris Avatar asked Aug 31 '26 00:08

Baris


1 Answers

*ngFor directive by default supports iterables like arrays. Here you could try to use the keyvalue pipe (Angular v6.1.0+) to iterate over objects. Try the following

<div *ngFor="let sport of sportsObject | keyvalue">
  <p>The {{ sport.key }} is {{ sport.value.ticketPrice }}</p>
  <p>More Info: <a [attr.href]="sport.value.link">{{ sport.value.link }}</a></p>
</div>

Also as a sidenote, it's generally better to avoid calling functions in directive bindings ([dir]="someFunc()" and *dir="someFunc()") and interpolations ({{ someFunc() }}). The reason is if you aren't controlling the change detection strategy, then the functions would be triggered for each CD cycle and might lead to performance issues.

like image 105
ruth Avatar answered Sep 03 '26 19:09

ruth