Search code examples
angularangular-directivengforangular9

Angular 9 *ngFor loop skipping some objects in an array


I'm trying to display the contents of an array of objects in four columns per table row:

Right now this just displays the index to help me see what's going on.

<tr *ngFor="let object of myObjects; let i = index">
  <div *ngIf="i % 4 == 0">
    <td *ngIf="i % 1 == 0">{{ i }}</td>
    <td *ngIf="i % 2 == 0">{{ i+1 }}</td>
    <td *ngIf="i % 3 == 0">{{ i+2 }}</td>
    <td *ngIf="i % 4 == 0">{{ i+3 }</td>
  </div>
</tr>

When I view the page it doesn't display all objects. I see something like this:

0 1 2 3
4 5 7
8 9 11

My question is, why is it skipping some of the objects?


Solution

  • Because your logic (using modulo === 0) is telling it to skip them.

    Here's your logic, but console logging the results.

    let foo = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    foo.forEach(item => { console.log("index is ", item, "and its % 4 === 0", item % 4 === 0, "item % 1 === 0", item % 1 === 0, "item % 2 === 0", item % 2 ===0, "item % 3 === 0", item % 3 === 0, "item % 4 === 0 (again)", item % 4 === 0)
    })