urosbelov
urosbelov

Reputation: 349

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>

Upvotes: 1

Views: 4864

Answers (2)

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

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>

Upvotes: 3

Mohammadreza Imani
Mohammadreza Imani

Reputation: 340

you can use 2d array for your table like below:

  lista = [
[
  {value: '1'},
  {value: '2'},
  {value: '3'},
  {value: '4'}
],

[
  {value: '5'},
  {value: '6'},
  {value: '7'},
  {value: '8'}
]
 ];

and for HTML

<table >
  <tr *ngFor="let row of lista">
    <td *ngFor="let col of row">
      <mat-checkbox>{{ col.value }}</mat-checkbox>
    </td>
  </tr>
</table> 

Upvotes: 0

Related Questions