Drprince100 100
Drprince100 100

Reputation: 79

How to read and display an array of arrays with *ngfor?

I have this array of arrays:

    (2) [Array(1), Array(2)]
    0: Array(1)
    0: {rank: "", role: "", summonerName: "adeus"}
    1: Array(2)
    0: {rank: "", role: "", summonerName: "olaaaaa"}
    1: {rank: "", role: "", summonerName: "olaaaaaaa"}

And I am using a simple *ngfor with a div to display the content of the array. But the problem is that I only know how to display the items inside the array, not the array inside the array.

so to get the summoner name I don't know what to do to get it because of this:

    <div *ngFor="let ola of test">
    
      <p> {{ola.summonerName}}</p>
    
    </div>

is not getting the array with the summoner name, it's getting the before that.

Upvotes: 1

Views: 2448

Answers (3)

mJehanno
mJehanno

Reputation: 866

You will need to use a nested *ngFor, with ngContainer :

<ng-container *ngFor="let arrays of test>
<div *ngFor="let ola of arrays ">

  <p> {{ola.summonerName}}</p>

</div>
</ng-container>

Why the <ng-container> ? because you can't apply more than one *ngFor/*ngIf on a html tag.

ng-container is an angular component that will not create any DOM element yet il will still display your div and apply the ngFor (without surcharging your page with more HTML).

Upvotes: 3

Barremian
Barremian

Reputation: 31105

You could just do a single level nested *ngFor. Try the following

<ng-container *ngFor="let arr of test">
  <div *ngFor="let ola of arr">
    <p> {{ ola?.summonerName }}</p>
  </div>
</ng-container>
  • Safe navigation operator ?. checks if the variable ola is defined before accessing it's property summonerName.
  • The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM. It gets commented in the DOM.

Upvotes: 2

barbara pugliatti
barbara pugliatti

Reputation: 46

You should try with nested *ngFor, the first one will loop the single array and the second his content

<div *ngFor="let array of arrayOfArrays">
    <div *ngFor="let element of array">
        <p> {{element.property}}</p>
    </div>
</div>

Upvotes: 0

Related Questions