You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中使用*ngFor配合Tailwind CSS实现表格两列循环展示

问题原因

你的*ngFor指令放置位置错误,当前你将循环写在<td>标签上,会导致所有otherClasses的条目都挤在同一行的多个单元格内,不符合「每条数据单独占一行」的常规表格渲染逻辑。

正确实现代码

方案1:每条课程数据单独占一行(最常用场景)

第一列保留原有课程跳转逻辑,第二列可根据业务需求替换为对应字段即可:

<table class="m-2 lg:m-8">
  <thead>
    <tr>
      <th class="w-1/2">Col 1</th>
      <th class="w-1/2">Col 2</th>
    </tr>
  </thead>
  <tbody>
    <!-- *ngFor绑定到tr标签,每条数据对应一行 -->
    <tr *ngFor="let c of otherClasses">
      <td>
        <menu-link
          [entry]="{
            url: c.external_url,
            site: 'oasis',
            path: ['class', c.slug]
          }"
          >{{ c.title }}</menu-link
        >
      </td>
      <td>
        <!-- 此处替换为第二列要展示的字段,比如课程时长、难度等 -->
        {{ c.desc }}
      </td>
    </tr>
    <!-- 最后一行额外的链接,跨两列展示 -->
    <tr>
      <td colspan="2">
        <a target="_blank" href="https://expium.com/"
          >Atlassian training, offered by our sister company Expium</a
        >
      </td>
    </tr>
  </tbody>
</table>

方案2:课程分左右两列排布

如果需求是所有课程分为两列并行展示,可使用如下实现:

<table class="m-2 lg:m-8">
  <thead>
    <tr>
      <th class="w-1/2">Col 1</th>
      <th class="w-1/2">Col 2</th>
    </tr>
  </thead>
  <tbody>
    <!-- 每两个课程占一行,分两列展示 -->
    <ng-container *ngFor="let c of otherClasses; let i = index">
      <tr *ngIf="i % 2 === 0">
        <td>
          <menu-link
            [entry]="{
              url: otherClasses[i].external_url,
              site: 'oasis',
              path: ['class', otherClasses[i].slug]
            }"
            >{{ otherClasses[i].title }}</menu-link
          >
        </td>
        <td *ngIf="i+1 < otherClasses.length">
          <menu-link
            [entry]="{
              url: otherClasses[i+1].external_url,
              site: 'oasis',
              path: ['class', otherClasses[i+1].slug]
            }"
            >{{ otherClasses[i+1].title }}</menu-link
          >
        </td>
        <td *ngIf="i+1 >= otherClasses.length"></td>
      </tr>
    </ng-container>
    <tr>
      <td colspan="2">
        <a target="_blank" href="https://expium.com/"
          >Atlassian training, offered by our sister company Expium</a
        >
      </td>
    </tr>
  </tbody>
</table>

内容的提问来源于stack exchange,提问作者Allison Barnett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:57:02