如何在ngx数据表中显示嵌套数组对象?

How to display nested array objects in ngx datatable?

我正在尝试从 ngx 数据表列中的嵌套数组中获取对象数据,有人可以帮我怎么做吗?请找我的例子

https://stackblitz.com/edit/angular-ngx-datatable-kglni5?file=app%2Fapp.component.ts[enter link description here]1

您可以使用 <ng-template> 为您的列定义 cellTemplate 以自定义列中显示的值。

解决方案 1

.component.html

<ng-template #batterTemplate let-row="row" let-value="value" let-i="index">
    <ng-template ngFor let-obj [ngForOf]="value">
        <strong> ID: {{ obj.id }} </strong>
        <span>Type: {{ obj.type }}</span>
        <br />
    </ng-template>
</ng-template>

<ng-template #toppingTemplate let-row="row" let-value="value" let-i="index">
    <ng-template ngFor let-obj [ngForOf]="value">
        <strong> ID: {{ obj.id }} </strong>
        <span>Type: {{ obj.type }}</span>
        <br />
    </ng-template>
</ng-template>

并确保您需要 OnInitAfterViewInit 方法 中使用 cellTemplate 定义列,因此 ngx-datatable 将生效。

.component.ts

export class AppComponent implements OnInit {
  @ViewChild('batterTemplate') batterTemplate!: TemplateRef<any>;
  @ViewChild('toppingTemplate') toppingTemplate!: TemplateRef<any>;

  ...

  columns = [];

  ngOnInit() {
    this.columns = [
      { name: 'Name', prop: 'name' },
      { name: 'Batters', prop: 'batters.batter', cellTemplate: this.batterTemplate },
      { name: 'Toppings', prop: 'topping', cellTemplate: this.toppingTemplate }
    ];
  }
}

Sample Solution 1 on StackBlitz


解决方案 2:

是的,您可以 <ng-template ngx-datatable-cell-template> 包裹在 <ngx-datatable-column> 中。

.component.html

<ngx-datatable 
  [rows]="rows" 
  class="material" 
  [loadingIndicator]="loadingIndicator"
  [columnMode]="'force'" 
  [headerHeight]="50" 
  [footerHeight]="50" 
  [rowHeight]="'auto'"
  [columns]="columns" 
  [reorderable]="reorderable">

    <ngx-datatable-column name="Name" prop="name"></ngx-datatable-column>

    <ngx-datatable-column name="Batter" prop="batters.batter">
        <ng-template let-row="row" let-value="value" let-i="index" ngx-datatable-cell-template>
            <ng-template ngFor let-obj [ngForOf]="value">
                <strong> ID: {{ obj.id }} </strong>
                <span>Type: {{ obj.type }}</span>
                <br />
            </ng-template>
        </ng-template>
    </ngx-datatable-column>

    <ngx-datatable-column name="Toppings" prop="topping">
        <ng-template let-row="row" let-value="value" let-i="index" ngx-datatable-cell-template>
            <ng-template ngFor let-obj [ngForOf]="value">
                <strong> ID: {{ obj.id }} </strong>
                <span>Type: {{ obj.type }}</span>
                <br />
            </ng-template>
        </ng-template>
    </ngx-datatable-column>

</ngx-datatable>

Sample Solution 2 on StackBlitz