简体   繁体   中英

Access nested json object angular 6

I'm trying to access the nested data from the HTML template, but I get undefined or I get nothing as result (empty page with no class list or student list).

The HTML template:

<div class="container">
        <label *ngFor="let class of listClass | keyvalue">
            <span> {{class.value.name}} </span>
        </label>

    <div>
        <label *ngFor="let student of class.students | keyvalue">
            <span>{{student.value.fullName}} </span>
        </label>
    </div>
</div>

This is the fonction that gets the list of class and the students in it:

getListClasseStudent(){
        this.classService.getStudents().subscribe((data) => {
            this.listClass = data;
        });
    }

The nested data:

class:
0:{
   code: "Math01"
   teacher: 
      0: {id: 17551, name "Jack"}
   students: 
      0: {studentId: 1, fullName: "Patrick bob"}
      1: {studentId: 2, fullName: "Alice Alice"}
}
1:{
   code: "English01"
   teacher: 
      0: {id: 2, name "Nicolas"}
   students: 
      0: {studentId: 1, fullName: "Patrick bob"}
      1: {studentId: 2, fullName: "Alice Alice"}
}

I want to access to the list of student of each class, is there any efficient way to do it? thanks in advance.

<div class="container">
<div *ngFor="let c of listClass ">
    <label >
        <span> {{c.code}} </span>
    </label>
    <div>
        <label *ngFor="let student of c.students ">
        <span>{{student.fullName}} </span>
    </label>
    </div>
</div>

Try this (example without your pipe)

A 'Class' object don't have a attribute 'value.name' (probably gonna be injected by your pipe '| keyvalue' ). Second *ngFor need t be inside of first, because he need's to iterate a students array, inside each class.

I hope this helps.

create a pipe like below

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
    transform(value: Object): Array<string> { return Object.keys(value); }
}

import the above pipe in app.module.ts and use pipe in the html page like below

 <div *ngFor="let key of questions | ObjNgFor" class="row">

    {{ questions[key].name}}

<div *ngFor="let r of questions[key].sub_sections | ObjNgFor ; let indx=index" 
   class="card-body"> 

{{ questions[key].sub_sections[r].name }}"

</div>

This example should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM