【问题标题】:Table in Angular 2Angular 2 中的表格
【发布时间】:2017-09-14 02:30:52
【问题描述】:

我想在 Angular 2 中建立一个表格。

这个表应该是这样的

我有一个Component,它给我一个数据

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

这是我的Template

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

但这是我得到的

我怎样才能实现我需要的表格? 以及如何在包含消息“不存在!”的表格单元格中插入?

【问题讨论】:

  • 不清楚['app1', 'item1', 'item2', 'item3', 'app2', 'item4', 'item5', 'item6', 'app3', 'item7', 'item8', 'item9'] 如何映射到表格。您至少可以在数组中使用与图像相同的部分和页面项。
  • @dfsq 抱歉,我的错 - 我通过添加新屏幕截图编辑了问题
  • 检测到该项目不存在以便插入它的规则是什么?您的数据结构不支持任何逻辑
  • 这只是来自json的消息,所以我尝试在某个plave上推入,但它不起作用,所以我想我需要为此多写一列

标签: javascript html css angular typescript


【解决方案1】:

你只需要用你的“不存在”文本来填充每一行的其余部分。如果你可以将你的 items 数组变成一个列表,那么肯定有一种更优化的方法来做到这一点对象或地图。

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

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>

【讨论】:

    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 2018-08-24
    相关资源
    最近更新 更多