Search code examples
javascriptangulartypescriptloopsangular-template

Angular 7 iterate table


I want to iterate table with one property but to have 4 td in one row, and to continue like that till the end...

I want like this:

<table>
      <tr>
        <td>
          <mat-checkbox>1</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>2</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>3</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>4</mat-checkbox>
        </td>
      </tr>
      <tr>
        <td>
          <mat-checkbox>5</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>6</mat-checkbox>
        </td>
        <td>
          <mat-checkbox>7</mat-checkbox>
        </td>
      </tr>
    </table>

I tried like this, but it's al in one column :

lista = [
    { value: "1" },
    { value: "2" },
    { value: "3" },
    { value: "4" },
    { value: "5" },
    { value: "6" },
    { value: "7" },
<table *ngFor="let list of lista">
   <tr>
     <td>
       <mat-checkbox>{{ list.value }}</mat-checkbox>
     </td>
   </tr>
</table>

Solution

  • You need to group your array firstly in groups of 4 (chunk size), then iterate over it simply in your template.

    In your component:

    const lista = [
        { value: "1" },
        { value: "2" },
        { value: "3" },
        { value: "4" },
        { value: "5" },
        { value: "6" },
        { value: "7" }
    ];
    
    const chunkSize = 4;
    
    // Group in chunks of 4 and take only truthy values
    const groups = lista
    .map((x, index) => { 
         return index % chunkSize === 0 ? lista.slice(index, index + chunkSize): null; 
    })
    .filter(x => x);
    

    In your template:

    <table >
       <tr *ngFor="let item of groups">
         <td *ngFor = "let innerItem of item">
           <mat-checkbox>{{ innerItem.value }}</mat-checkbox>
         </td>
       </tr>
    </table>