javascript - Angular 2 中的表格

标签 javascript html css angular typescript

我想在 Angular 2 中构建一个表。

这张表应该是这样的

enter image description here

我有一个组件,它给我一个数据

export class ResultsComponent implements OnInit {
  public items: any;

  ngOnInit() {
    this.items = ['app1', 'item1', 'item2', 'item3', 'app2', 'item4',
            'item5', 'item6', 'app3', 'item7', 'item8', 'item9'];
    this.buildArr(this.items);
  }

  buildArr(theArr: any[]) {
    const arrOfarr = [];
    for (let i = 0; i < theArr.length ; i += 4) {
      const row = [];
      for (let j = 0; j < 4; j++) {
        const value = theArr[i + j];
        if (!value) {
          break;
        }
        row.push(value);
      }
      arrOfarr.push(row);
    }
    return arrOfarr;
  }

这是我的模板

<h1>Results</h1>
<table class="table" id="myTable" class="table">
  <thead>
  <tr>
    <th></th>
    <th>Part 1</th>
    <th>Part 2</th>
    <th>Part 3</th>
    <th>Part 4</th>
  </tr>
  </thead>
  <tbody>

  <tr *ngFor="let row of buildArr(items);let i = index">
    <td *ngFor="let item of row">{{item}}</td>
  </tr>
  </tbody>
</table>

但这是我得到的

The result

我怎样才能得到我需要的表格? 我怎样才能插入包含消息“不存在!”的表格单元格?

最佳答案

您只需要用“不存在”文本填写每一行的其余部分。如果您可以将元素数组转换为列表,肯定有更优化的方法来执行此操作对象或 map 。

下面显示的是对现有代码的一个小改动,用“不存在”文本填充索引

export class ResultsComponent implements OnInit {
  public items: any;

  ngOnInit() {
    this.items = ['app1', 'item1', 'item2', 'item3', 'app2', 'item4',
      'item5', 'item6', 'app3', 'item7', 'item8', 'item9'
    ];

    this.buildArr(this.items);
  }

  buildArr(theArr: any[]) {
    const arrOfarr = [];
    for (let i = 0; i < theArr.length; i += 4) {
      const row = [];
      for (let j = 0; j < 4; j++) {
        const value = theArr[i + j];
        if (j > 0 && value.substring(0, 2) == "app") { //make sure to skip first item
          while (j < 4) { //finish off row with placeholder string
            row[j] = "does not exist"
          }
          break;
        }
        row.push(value);
      }
      arrOfarr.push(row);
    }
    return arrOfarr;
  }
<h1>Results</h1>
<table class="table" id="myTable" class="table">
  <thead>
    <tr>
      <th></th>
      <th>Part 1</th>
      <th>Part 2</th>
      <th>Part 3</th>
      <th>Part 4</th>
    </tr>
  </thead>
  <tbody>

    <tr *ngFor="let row of buildArr(items);let i = index">
      <td *ngFor="let item of row">{{item}}</td>
    </tr>
  </tbody>
</table>

关于javascript - Angular 2 中的表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45843138/

相关文章:

jquery - 向字符串表添加样式不起作用

javascript - Angularjs 中带有复选框的动态表单字段

html - 将充满图像的 HTML 表格转换为在移动设备上看起来不错

html - 菜单在移动 View 中占用空间

html - 如何在 CSS 网格布局中指定行高?

javascript - 如何创建 Angularjs 部分更新(补丁)?

javascript - 组件按钮最初显示 'n' 个 div 元素,然后显示 'n' 个更多元素

javascript - 机车滚动如何让元素固定在滚动条上

javascript - 在 Laravel 中使用 ajax FormData() 时无法获取输入字段的值

javascript - 如何让工作网格显示来自 ajax 的数据源?