skip to Main Content

I am making a front-end for my PHP project using Angular and I want to make a HTML table, with specified width and height, using just *ngFor and indexes and show items of an one-dimensional array. I have a PHP code that looks like this:

$items = array("Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6"); // belongs in .ts file

// belongs in .html file
echo "<table>";

for ($i = 0; $i < 2; $i++) {
    echo "<tr>";

    for ($j = 0; $j < 3; $j++) {
        echo "<td>" . $items[$i * 3 + $j] . "</td>";
    }
    
    echo "</tr>";
}

echo "</table>

How do I do this in Angular? *ngFor="let item in items" is Angular equivalent to foreach ($items as item), which is a thing that I don’t want.

2

Answers


  1. You can set an index like this:

    <tr *ngFor="let item of items; index as i">
      {{i}}
    </tr>
    

    And manipulate the outcome depending what you are trying achieve, above I’ve just listed all the indexes of the items array. You can also nest a loop inside, and control which element to show or hide(they wont be in the DOM Object) with *ngIf:

    <tr *ngFor="let item of items; index as i">
      <td *ngFor="let detail of details; index as i>
        <ng-container *ngIf="X"
          //where X is anything that returns a boolean, a variable, function or even truthy value
           {{detail}}
        </ng-container>
      </td>
    </tr>
    
    Login or Signup to reply.
  2. In Angular *ngFor always iterate over arrays, there’ no any like for (i=0;i<10;i++)

    But you can create the array in the own .html

    <table>
      <tr *ngFor="let i of [0,1]">
        <td *ngFor="let j of [0,1,2]">
           {{{items[i*3+j]}}
        </td>
      </tr>
    </table>
    

    NOTE: Really you can also create a directive that simulate a php for, see e.g. this old post about it

    NOTE2: I use simply items, not $items because in Angular is common use the $ in variables only when the variable is an observable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search