【问题标题】:Dynamic colspan in AngularAngular中的动态colspan
【发布时间】:2021-11-30 11:02:57
【问题描述】:

频段和天线的数量是动态的。我需要将这些数据显示在表格中。

active_bands_to_antennas = [
 {
   band: "Blue",
   antennas: ["One", "Two" "Three"]
},
{
   band: "Red",
   antennas: ["Four", Five"]
} 
]

模板:

<tr>
  <th>&nbsp</th>
  <th *ngFor="let data of active_bands_to_antennas" [attr.colspan]="data.antennas.length">{{data.band}}</th>
  <th>&nbsp</th>
  <th>&nbsp</th>
</tr>

预期输出:

table, th, td {
    border: 1px solid black;
}
<table>
  <tr>
    <td>&nbsp</td>
    <td colspan="3">Blue</td>
    <td colspan="2">Red</td>
    <td>&nbsp</td>
    <td>&nbsp</td>
  </tr>
  <tr>
    <td>&nbsp</td>
    <td>One</td>
    <td>Two</td>
    <td>Three</td>
    <td>Four</td>
    <td>Five</td>
    <td>&nbsp</td>
    <td>&nbsp</td>
  </tr>
</table>

一切正常。除了波段显示在多行而不是仅一行(取决于波段的数量)。

电流输出:

table, th, td {
    border: 1px solid black;
}
<table>
      <tr>
        <td>&nbsp</td>
        <td colspan="3">Blue</td>
        <td>&nbsp</td>
        <td>&nbsp</td>
      </tr>
      <tr>
        <td>&nbsp</td>
        <td colspan="2">Red</td>
        <td>&nbsp</td>
        <td>&nbsp</td>
      </tr>
      <tr>
        <td>&nbsp</td>
        <td>One</td>
        <td>Two</td>
        <td>Three</td>
        <td>Four</td>
        <td>Five</td>
        <td>&nbsp</td>
        <td>&nbsp</td>
      </tr
    </table>

这就是我实现“colspan”的想法的地方:Dynamic rowspan in angular

【问题讨论】:

    标签: html angular html-table


    【解决方案1】:

    要获得所需的输出,一种可能的方法是从antennas 属性创建“数组数组”。

    const arrayOfArrays = this.active_bands_to_antennas.map((x) => x.antennas);
    

    在这之后你会得到一个数组 = [ ['One', 'Two', 'Three'], ['Four', 'Five'] ];

    然后你可以把它展平得到一个一维数组:['One', 'Two', 'Three', 'Four', 'Five']

    HTML 基本上是两个循环,一个用于标题,一个用于天线。

    <table>
      <tr>
        <th>&nbsp</th>
        <th
          *ngFor="let band of active_bands_to_antennas"
          [attr.colspan]="band.antennas.length"
        >
          {{ band.band }}
        </th>
        <th>&nbsp</th>
        <th>&nbsp</th>
      </tr>
      <tr>
        <td *ngFor="let ant of antennas">
          {{ ant }}
        </td>
      </tr>
    </table>
    

    工作Stackblitz

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      相关资源
      最近更新 更多