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

Loop on array of arrays – Angular

I’m getting an array of arrays from a service and i want to display case [0] and [1] on each iteration, but when I do that i get an error TypeError: Cannot read properties of undefined (reading ‘0’)

      <ng-container
                *ngFor="let done of this.launch.doneAreas; index as i">
                <div class="display-result">
                  Case n° {{ i + 1 }} => ({{ done[i][0] }},{{ done[i][1] }})
                </div>
      </ng-container>

The array is defined like this in the service:

  doneAreas: any[][] = [];

and I’m pushing values by pushing an array of numbers into it. coords beeing an array of two numbers.

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

  this.doneAreas.push(this.coords);

Here’s an example of the array i want to display when I console.log it.

0: (2) [3, 3]

1: (2) [3, 4]

2: (2) [4, 4]

3: Array(2)
0: 4
1: 3
length: 2
[[Prototype]]: Array(0)

Thanks

>Solution :

You could make a dynamic object {x: number, y: number}. If you use that in a list you can ensure both should be present.

Your issue is that done already is an object and you are trying to get the index of an array that is not present.

doneAreas: {x: number, y: number}[] = [];
this.doneAreas.push({this.coords.x, this.coords.y);
<ng-container
          *ngFor="let done of this.launch.doneAreas; index as i">
          <div class="display-result">
            Case n° {{ i + 1 }} => ({{ done.x }},{{ done.y }})
          </div>
</ng-container>

If you want to keep the code as it is you should just remove [I]:

      <ng-container
                *ngFor="let done of this.launch.doneAreas; index as i">
                <div class="display-result">
                  Case n° {{ i + 1 }} => ({{ done[0] }},{{ done[1] }})
                </div>
      </ng-container>
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