0
votes

I have a json array and i want to print the values in a simple list. How to print the values? Do I have to follow key value method? I'm adding my Json array structure and my sample code. It is showing me errors.

Expected Output

*456
*123

or Arun :123 
test:456

Error:

"'[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

Json Array

   {
        "records": [{
            "arun": [1, 2, 3],
            "test": [4, 5, 6]
        }]
    }

**myTest.ts**

export class HomePageComponent extends AppComponent {

  public bundle:  any[];

   ngOnInit(){
     this.readArray();
   }

   readArray() {
    this.bundle =  {
        "records": [{
            "arun": [1, 2, 3],
            "test": [4, 5, 6]
        }]
    }
    console.log("array",this.bundle);
   }

testComponent.html

<ul *ngFor="let det of bundle;">
  <li>{{det.records}}</li>
</ul>
2

2 Answers

2
votes

You need to use ngFor over an array, it should be <div *ngFor="let record of bundle.records"> , also you have a nested array, you can access the items using Object.keys as in the demo

@Component({
  selector: 'my-app',
  template: `
   <div *ngFor="let record of bundle.records">
      <ul *ngFor="let key of objectKeys(record)">
         <li>{{key}} :: {{record[key]}}</li>
      </ul>
   </div>
  `,
})

DEMO

0
votes

Have Object.keys accessible in the template and use it in *ngFor.

  export class HomePageComponent extends AppComponent {
  objectKeys = Object.keys;

then in your template

 <ul *ngFor="let key of objectKeys(bundle.records[0]);">
    <li>{{key + ' : ' + bundle.records[0][key]}}</li>
  </ul>