1 import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';
3 import * as _ from 'lodash';
5 import { CellTemplate } from '../../enum/cell-template.enum';
6 import { CdTableColumn } from '../../models/cd-table-column';
9 * Display the given data in a 2 column data table. The left column
10 * shows the 'key' attribute, the right column the 'value' attribute.
11 * The data table has the following characteristics:
12 * - No header and footer is displayed
13 * - The relation of the width for the columns 'key' and 'value' is 1:3
14 * - The 'key' column is displayed in bold text
17 selector: 'cd-table-key-value',
18 templateUrl: './table-key-value.component.html',
19 styleUrls: ['./table-key-value.component.scss']
21 export class TableKeyValueComponent implements OnInit, OnChanges {
22 columns: Array<CdTableColumn> = [];
27 autoReload: any = 5000;
30 renderObjects = false;
31 // Only used if objects are rendered
33 appendParentKey = true;
41 * The function that will be called to update the input data.
44 fetchData = new EventEmitter();
53 cellTransformation: CellTemplate.bold
63 ngOnChanges(changes) {
69 return; // Wait for data
71 this.tableData = this._makePairs(this.data);
74 _makePairs(data: any) {
77 return; // Wait for data
78 } else if (_.isArray(data)) {
79 temp = this._makePairsFromArray(data);
80 } else if (_.isPlainObject(data)) {
81 temp = this._makePairsFromObject(data);
83 throw new Error('Wrong data format');
85 temp = temp.map((v) => this._convertValue(v)).filter((o) => o); // Filters out undefined
86 return this.renderObjects ? this._insertFlattenObjects(temp) : temp;
89 _makePairsFromArray(data: any[]) {
91 const first = data[0];
92 if (_.isPlainObject(first)) {
93 if (_.has(first, 'key') && _.has(first, 'value')) {
96 throw new Error('Wrong object array format: {key: string, value: any}[]');
99 if (_.isArray(first)) {
100 if (first.length === 2) {
101 temp = data.map((a) => ({
106 throw new Error('Wrong array format: [string, any][]');
113 _makePairsFromObject(data: object) {
114 return Object.keys(data).map((k) => ({
120 _insertFlattenObjects(temp: any[]) {
121 temp.forEach((v, i) => {
122 if (_.isPlainObject(v.value)) {
124 this._makePairs(v.value).forEach((item) => {
125 if (this.appendParentKey) {
126 item.key = v.key + ' ' + item.key;
128 temp.splice(i, 0, item);
136 _convertValue(v: any) {
137 if (_.isArray(v.value)) {
139 .map((item) => (_.isPlainObject(item) ? JSON.stringify(item) : item))
141 } else if (_.isPlainObject(v.value) && !this.renderObjects) {
148 // Forward event triggered by the 'cd-table' datatable.
149 this.fetchData.emit();