Home > other >  How to iterate over arrays in angular 12?
How to iterate over arrays in angular 12?

Time:09-22

I am trying to iterate over an object that's in an array of an array, however, I'm not able to display the data in the front-end.

I tried this method:

<div *ngFor="let item of events of event | keyvalue">
    {{item.key}}:{{item.value}}
</div>

and this one:

<div *ngFor="let item of events of event | json">
   Test: {{item}}
</div>

The structure of the JSON data is given in this format.

[
    [
        {
            "age": "age3",
            "gender": "gender3"
        },
        {
            "age": "age3",
            "gender": "gender3"
        }
    ]
]

CodePudding user response:

It looks likes a nested array, try using multiple ngFor:

<div *ngFor="let event of events">
  <div *ngFor="let item of event">
    Test: {{item | json}}
  </div>
</div>

Otherwise you could try using Array.prototype.flat to flatten the nested array:

this.flattened = this.events.flat();

// ...

<div *ngFor="let item of flattened">
  Test: {{item | json}}
</div>

CodePudding user response:

<ng-container> is fine when you want structural logic without polluting the DOM with useless elements.

<ng-container *ngFor="let subArray of array"> <!-- This does not appear in the DOM -->
  <div *ngFor="let item of subArray"> <!-- This appears in the DOM -->
    {{item.key}}:{{item.value}}
  </div>
</ng-container>

CodePudding user response:

You'll have to iterate through each internal array as well, so you'll need a nested *ngFor. Make sure to reference the correct item array in your nested *ngFor.

<div *ngFor = "let item of events">
    <div *ngFor = "let x of item">
        {{x.age}}:{{y.gender}}
    </div>
</div>
  • Related