Angular динамическое отображение таблицы матов c пара значений ключа в каждой строке - PullRequest
0 голосов
/ 14 марта 2020

У меня есть данные пары ключ-значение в формате JSON. Ключи будут динамическими c по своей природе. Не существует определенного c набора ключей, который будет частью JSON. Я хочу показать их в табличном формате, используя Angular mat-table.

var data = {
 "cars" : 24,
 "fruit" : "apple",
 "phone" : "Iphone",
 "food" : "Burger"
};

Мой вывод таблицы должен быть:

  • заголовок таблицы должен содержать 2 столбца KEY и VALUE
  • данные каждой строки должны быть выше значения ключа Dynami c json.

Ожидаемый вывод таблицы:

Expected table output:

Ответы [ 2 ]

0 голосов
/ 14 марта 2020

Нет необходимости преобразовывать объект в массив. Вы можете легко использовать keyvalue pipe.

В файле ts:

// properties of the class
displayedColumns: string[] = ['key', 'value'];
dataSource = data;

// use this method if you want to keep the order of the object properties
public orderByKey(a, b) {
    return a.key;
  }

В файле html:

<table mat-table [dataSource]="dataSource | keyvalue:orderByKey" class="mat-elevation-z8">
  <ng-container matColumnDef="key">
    <th mat-header-cell *matHeaderCellDef> Key </th>
    <td mat-cell *matCellDef="let element"> {{element.key}} </td>
  </ng-container>

  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef> Value </th>
    <td mat-cell *matCellDef="let element"> {{element.value}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

Вы можете проверить, как это работает в этот стек * блиц

0 голосов
/ 14 марта 2020

Преобразуйте ваш объект в массив

  dataSource = [];
  var data = {
    cars: 24,
    fruit: "apple",
    phone: "Iphone",
    food: "Burger"
  };

  for (const key in data) {
    dataSource.push({ key, value: data[key] });
  }

и используйте его в angular материале

.ts файла

import { Component } from "@angular/core";
export interface RowElement {
  key: string;
  value: string;
}
@Component({
  selector: "table-basic-example",
  styleUrls: ["table-basic-example.css"],
  templateUrl: "table-basic-example.html"
})
export class TableBasicExample {
  data = {
    cars: 24,
    fruit: "apple",
    phone: "Iphone",
    food: "Burger"
  };

  displayedColumns: string[] = ["key", "value"];
  dataSource: RowElement[];

  constructor() {
    for (const key in this.data) {
      this.dataSource.push({ key, value: this.data[key] });
    }
  }
}

. html файла

<table mat-table [dataSource]="dataSource">
  <!-- Key Column -->
  <ng-container matColumnDef="key">
    <th mat-header-cell *matHeaderCellDef>Key</th>
    <td mat-cell *matCellDef="let element">{{element.key}}</td>
  </ng-container>

  <!-- Value Column -->
  <ng-container matColumnDef="value">
    <th mat-header-cell *matHeaderCellDef>Value</th>
    <td mat-cell *matCellDef="let element">{{element.value}}</td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...