首页 > 解决方案 > Angular 7迭代表

问题描述

我想用一个属性迭代表,但在一行中有 4 个 td,并继续这样直到结束......

我想要这样:

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

我试过这样,但它在一列中:

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>

标签: javascriptangulartypescriptloopsangular-template

解决方案


您需要首先将数组分组为4(块大小)组,然后在模板中简单地对其进行迭代。

在您的组件中:

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);

在您的模板中:

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

推荐阅读