【问题标题】:How to fill data in the table columns and rows dynamically如何动态填充表格列和行中的数据
【发布时间】:2018-12-24 13:46:33
【问题描述】:

我从 api 获取字符串数组并需要在表中显示它们(word1、word2、word3 等)。我不知道具体会是多少。表中的列数应为 5,行数取决于此数组。

                    <tr>
                        <th><a href="#">Cell 1</a></th>
                        <th><a href="#">Cell 2</a></th>
                        <th><a href="#">Cell 3</a></th>
                        <th><a href="#">Cell 4</a></th>
                        <th><a href="#">Cell 5</a></th>
                    </tr>
                    <tr>
                        <th><a href="#">Cell 6</a></th>
                        <th><a href="#">Cell 7</a></th>
                        <th><a href="#">Cell 8</a></th>
                        <th><a href="#">Cell 9</a></th>
                        <th><a href="#">Cell 9</a></th>
                    </tr>

如果有 20 个项目 - 应该是 4 行。我不知道如何开始新行。 示例是按行填充,如下所示显示如何按行填充

  <tr *ngFor="let tablerows of data">
                      <td>
                      {{tablerows.row_id}}
                      </td>
                      <td>{{tablerows.number}}</td>
                      <td >{{tablerows.employee_name}}</td>
                      <td >{{tablerows.manager_name}}
                      </td>
                    </tr>

是否可以通过角度来做到这一点?或者也许我应该在组件中创建一些数组?

【问题讨论】:

  • 你在用材料吗?
  • @programoholic 引导
  • 你能发布行 json 的样本吗?

标签: angular html-table


【解决方案1】:

这可能很糟糕,但是因为以这种方式操作字符串数组而不是需要的对象数组也很糟糕,所以这里是:

在组件中,将您的数组拆分为长度为 5 的子数组并将它们推送到一个新数组中,如下所示:

ngOnInit(){
  for (var i = 1; i <= 25; i++) {
    this.foo.push(i);
 }

 for(let x=0; x<this.foo.length; i+5){
  this.bar.push(this.foo.splice(x,x+5));
 }

}

我使用了一个数值数组来显示。在 html 中,您现在可以忽略 foo 并且只在 bar 上工作,如下所示:

  <table style="border:1px solid">          
      <tr *ngFor="let qwe of bar" style="border:1px solid">
        <td *ngFor="let asd of qwe" style="border:1px solid"> {{asd}}</td>
      </tr>
  </table>

我知道这不完全是你的情况,但我认为你可以从这里计算出你的逻辑(我猜你可能无法在 s 上循环,因为你有特定的密钥可以访问,但仍然:) )

【讨论】:

  • 非常感谢,我现在可以成功了。您提到最好有一个对象数组,我也可以得到它。这种情况下会有什么区别?
  • 在我的示例中,您只需使用数字 id 按顺序进行。如果您收到一个包含键值对的对象数组,您可以按任何顺序访问它们,并且代码将更具可读性。此外,您不需要在组件中手动将“foo”转换为“bar”,您已经可以直接从 API 中获得“bar”。
猜你喜欢
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 2015-07-03
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多