具有动态行和列的angular2表 [英] angular2 table with dynamic rows and columns

查看:174
本文介绍了具有动态行和列的angular2表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在角度2中创建动态列和行的表

How do I create a table with dynamic columns and rows in angular2

我有一个来自休息服务的数据,并捕获在这个可观察的

I have the data coming from a rest service and captured in this observable

this._physicalDataService.getPhysicalData().subscribe(res=> this.data = res)

我可以通过此代码动态显示行。如何使列和列标题动态化,我如何提取数组中的所有JSON键,以将另一个循环放在顶端。

I can display the rows dynamically through this code. How do I make the columns and the column headers dynamic too ie how can i extract all the JSON keys in an array to put another loop on top.

澄清我的后端服务可能返回不同的列和行的不同数据集,我想在页面上动态显示。

To clarify my backend service may return different datasets with different columns and row and I want to show them dynamically on a page.

               <thead class="no-bd">
                        <tr>
                          <th>Id</th>
                          <th>Number</th>
                          <th >Employee Name</th>
                          <th >Manager Name</th>
                        </tr>
                        </thead>

                        <tbody>

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


推荐答案

您可以在< th>< / th>

但是,为此,您需要计算Object的长度。给每个数组中的元素没有。

But For that you will need to calculate length of Object.It Will give you no of elements in each Array.

var custObject = new Object();
myArray["firstname"] = "Gareth";
myArray["lastname"] = "Simpson";
myArray["age"] = 21;
this.objLength = Object.keys(myArray).length;  // Calc length of Object i.e. 3

在你拥有对象的长度之后,你可以渲染你的< th> 阻止多次使用以下管道:

After You Have length of Object , You can render your <th> block that many times using below pipe:

<th *ngFor='#key of 5 | demoNumber;let i=index'>
Column{{i}}
</th>

管道:

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
  transform(value, args:string[]) : any {
    let res = [];
     for (let i = 0; i < value; i++) {
        res.push(i);
     }
    return res;
  }
}

这将计算对象字段&那么ngFor将为每个字段提供Coulmn +索引。

This will calculate no of Object fields & then ngFor will render Coulmn+index for each field.

希望这有帮助。

这篇关于具有动态行和列的angular2表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆