Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display nested JSON file in Angular

I can’t wrap my head around how I should loop through a nested JSON file I’ve got.

This is the code I’ve got si far:

JSON:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {  
    "produkt": "dammsugare",
    "produktinformation": [
        {
        "artikelnr": 9121283726,
        "typ": "ean"
        },
        {
        "artikelnr": "dasu",
        "typ": "varukod"
        }
    ]
    },
    {
    "produkt": "hammare",
    "produktinformation": [
        {
        "artikelnr": 91246128736,
        "typ": "ean"
        },
        {
        "artikelnr": "traffaspik",
        "typ": "varukod"
        }
    ]
    }
]

Service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MyserviceService {

  constructor(private http:HttpClient) { }

  getProducts() {
    console.log('getProducts()');
    return this.http.get('/assets/produkter.json');
  }

  getInfo() {
    console.log('getInfo()');
    return this.http.get('/assets/produkter.json')
  }
}

Component.ts:

import { Component, OnInit } from '@angular/core';
import { MyserviceService } from '../myservice.service';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {

  arrProducts: any;

  constructor(private myserviceService: MyserviceService) { }

  ngOnInit() {
    this.myserviceService.getProducts().subscribe((data) => {
      console.log(data);
      this.arrProducts = data;
    });
  }
}

Component.html:

<p>list works!</p>
<ul *ngFor="let product of arrProducts">
    <li>{{ product.produkt }}</li>
    <li>{{ product.productinformation.artikelnr }}</li> <!-- THIS LINE IS WRONG, BUT I DON'T KNOW WHAT TO DO-->
</ul>

As you can see, I do not know how to edit the component.html for it to display the nested JSON file.

I hope there’s someone who could help me out. Thanks! 🙂

>Solution :

you just nest ngFor

<p>list works!</p>
<ul *ngFor="let product of arrProducts">
    <li>{{ product.produkt }}</li>
    <li *ngFor="let info of product.produktinformation">{{ info.artikelnr }}</li>
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading