Home > Net >  Loop on array of arrays - Angular
Loop on array of arrays - Angular

Time:07-01

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 >
                  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.

  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

CodePudding user response:

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 >
            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 >
                  Case n° {{ i   1 }} => ({{ done[0] }},{{ done[1] }})
                </div>
      </ng-container>
  • Related