javascript 在primeng的列中显示嵌套对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48145549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:50:28  来源:igfitidea点击:

Display nested object in column in primeng

javascriptprimengprimeng-datatable

提问by RemyaJ

I am following the templating option given in primeng docs to create a link with column data alongside in a primeng datatable column, but I am not able to show nested object using {{data[col.field]}}.

我正在按照primeng 文档中给出的模板选项在primeng 数据表列中创建包含列数据的链接,但我无法使用{{data[col.field]}} 显示嵌套对象。

<p-column [field]="col.field" [header]="col.header" [sortable]="col.sortable" [filter]="col.filter" [editable]="col.editable" [filterPlaceholder]="col.filterPlaceholder" styleClass="{{col.class}}">
                <ng-template let-col let-data="rowData" let-ri="rowIndex" pTemplate="body">
                    <span *ngIf="!col.field.includes('.')" >{{data[col.field]}}</span>
                    <!-- <span *ngIf="col.field.includes('.')">{{data[col.field.split('.')[0]][col.field.split('.')[1]]}}</span> this does not work because field is like x.y-->
                    <!-- I have some other buttons here as well --> 
                </ng-template>
        </p-column>

How can I acheive this?

我怎样才能做到这一点?

Sharing entire code -->

共享整个代码-->

<p-dataTable [globalFilter]="gb" [filterDelay]=1000 [value]="tableData" [alwaysShowPaginator]="true" [rowStyleClass]="setStyle" [rows]="rows" [paginator]="paginate" [alwaysShowPaginator]="false" [resizableColumns]="true" tableStyleClass="table-wrap {{rowClass}}"
    [rowsPerPageOptions]="[5,10,20]" expandableRows="{{setExpander}}" [editable]="setEditable" (onRowClick)="handleRowSelect($event)" [lazy]="pagination" [totalRecords]="totalRecords" (onLazyLoad)="loadLazy($event)" [ngClass]="{'paginator-table': pagination}">
    <div *ngFor="let col of tableOptions.columns, let index=index, let odd=odd, let even=even">
        <p-column *ngIf="col.field" [field]="col.field" [header]="col.header" [sortable]="col.sortable" [filter]="col.filter" [editable]="col.editable" [filterPlaceholder]="col.filterPlaceholder" styleClass="{{col.class}}">
            <ng-template let-col let-data="rowData" let-ri="rowIndex" pTemplate="body">
                    <span *ngIf="!col.field.includes('.')" >{{data[col.field]}}</span>
                    <!-- <span *ngIf="col.field.includes('.')">{{data[col.field.split('.')[0]][col.field.split('.')[1]]}}</span> this does not work because field is like x.y-->
                <a *ngIf="col.field === 'ticket'" target="_blank" href={{link}}{{data[col.field]}}><i class="fa fa-external-link" aria-hidden="true"></i></a>
            </ng-template>
        </p-column>
    </div>
</p-dataTable>

回答by Bandeeta

PrimeNG DataTable is deprecated, use Table (AKA TurboTable) instead. https://www.primefaces.org/primeng-5-2-0-rc1-released-turbotable/

PrimeNG DataTable 已弃用,请改用 Table (AKA TurboTable)。https://www.primefaces.org/primeng-5-2-0-rc1-released-turbotable/

Anyways, you could access nested object inside Data-Table as follows:

无论如何,您可以按如下方式访问数据表中的嵌套对象:

<p-table [columns]="cols" [value]="data" ... >
  ...
  // Definition of table body
  <ng-template pTemplate="body" let-rowData let-columns="columns">
    <tr [pSelectableRow]="rowData">
      <td *ngFor="let col of columns">
         <div *ngIf="col.subfield;then nested_object_content else normal_content"></div>
         <ng-template #nested_object_content>
           {{rowData[col.field][col.subfield]}}
         </ng-template>
         <ng-template #normal_content>
           {{rowData[col.field]}}
         </ng-template>
      </td>
    </tr>
  </ngTemplate>
  ...
</p-table>

and in your component:

并在您的组件中:

public data = [
{
  field1: {
    subfield1: 'test'
  },
  field2: 'test',
  field3: 'test',
  field4: {
    subfield4: 'test'
  }
}]

this.cols = [
  { field: 'field1', subfield: 'subfield1'},
  { field: 'field2'},
  { field: 'field3'},
  { field: 'field4', subfield: 'subfield4'},
];

I hope this helps you. :)

我希望这可以帮助你。:)

回答by Stephanie

As a follow-up to what Bandeeta said about TurboTable: this solution can handle multiple nested properties instead of just one subfield:

作为 Bandeeta 关于 TurboTable 所说的后续内容:此解决方案可以处理多个嵌套属性,而不仅仅是一个子字段:

<tr [pSelectableRow]="row">
  <td *ngFor="let col of columns">
    <span>{{ getCellData(row, col) }}</span>
  </td>
</tr>

And in your component:

在您的组件中:

getCellData(row: any, col: any): any {
   const nestedProperties: string[] = col.field.split('.');
   let value: any = row;
   for (const prop of nestedProperties) {
     value = value[prop];
   }

   return value;
 }

回答by gkhnclk

You can do this using Angular Custom Pipe. Sample here.

您可以使用 Angular 自定义管道来做到这一点。样品在这里。

app.component.html

应用程序组件.html

<p-table [columns]="cols" [value]="cars">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns">
                {{col.header}}
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <td *ngFor="let col of columns">
                    {{rowData|field:col}}
            </td>
        </tr>
    </ng-template>
</p-table>

app.component.ts

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  cars = [
    {
      year: 2019,
      brand: {
        name: "Toyota"
      },
      color: "White",
      passengers: [
        {
          name: "John"
        }
      ]
    },
    {
      year: 2018,
      brand: {
        name: "Toyota"
      },
      color: "White",
      passengers: [
        {
          name: "Suzanne"
        }
      ]
    },
    {
      year: 2017,
      brand: {
        name: "Toyota"
      },
      color: "White",
      passengers: [
        {
          name: "G?khan"
        }
      ]
    }
  ];
  cols: any[];
  constructor() {}

  ngOnInit() {
    this.cols = [
      { field: "year", header: "Year" },
      { field: "brand.name", header: "Brand" },
      { field: "color", header: "Color" },
      { field: "passengers.0.name", header: "Passengers" }
    ];
  }
}

Running example is here.

运行示例在这里。

https://stackblitz.com/edit/angular6-primeng-qhxptl

https://stackblitz.com/edit/angular6-primeng-qhxptl

回答by jalex19

This might be a little bit late, but I ended up with a bit different solution. I have my own table component based on p-table and I bind the columns, rows, etc.

这可能有点晚了,但我最终得到了一个有点不同的解决方案。我有自己的基于 p-table 的表格组件,并绑定了列、行等。

I created a component specifically for this, then I bind the current row and column

我专门为此创建了一个组件,然后绑定当前行和列

<ng-template pTemplate="body" let-rowData let-columns="columns">
    <tr [pSelectableRow]="rowData">
        <td *ngFor="let col of columns">
          <app-table-column [column]="col" [row]="rowData"></app-table-column>
        </td>
    </tr>
</ng-template>

This is my table-column component, I'm sharing a very basic stuff but you can improve it as you wish/need.

这是我的表列组件,我正在分享一个非常基本的东西,但您可以根据需要/需要改进它。

I'm using lodash to get the row's value based on the field (column), it works for dotted (nested properties) or for flat properties.

我正在使用 lodash 根据字段(列)获取行的值,它适用于点(嵌套属性)或平面属性。

    import { Component, Input, OnInit } from '@angular/core';
import * as moment from 'moment';
import * as _ from 'lodash';

@Component({
  template: `
    <span>
      {{ value }}
    </span>
  `,
  selector: 'app-table-column',
})
export class TableColumnComponent implements OnInit{

  @Input() column;
  @Input() row;

  value: any;

  constructor() {}

  ngOnInit(): void {
    this.parseValue(_.get(this.row, this.column.field));
  }

  parseValue(value) {
    switch (this.column.type) {
      case 'date':
        this.value = moment(value);
        break;

      default:
        this.value = value;
      break;
    }
  }

}