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> = [];
25 @Input() autoReload: any = 5000;
27 @Input() renderObjects = false;
28 // Only used if objects are rendered
29 @Input() appendParentKey = true;
37 * The function that will be called to update the input data.
39 @Output() fetchData = new EventEmitter();
48 cellTransformation: CellTemplate.bold
58 ngOnChanges(changes) {
64 return; // Wait for data
66 this.tableData = this._makePairs(this.data);
69 _makePairs(data: any) {
72 return; // Wait for data
73 } else if (_.isArray(data)) {
74 temp = this._makePairsFromArray(data);
75 } else if (_.isPlainObject(data)) {
76 temp = this._makePairsFromObject(data);
78 throw new Error('Wrong data format');
80 temp = temp.map((v) => this._convertValue(v)).filter((o) => o); // Filters out undefined
81 return this.renderObjects ? this._insertFlattenObjects(temp) : temp;
84 _makePairsFromArray(data: any[]) {
86 const first = data[0];
87 if (_.isPlainObject(first)) {
88 if (_.has(first, 'key') && _.has(first, 'value')) {
91 throw new Error('Wrong object array format: {key: string, value: any}[]');
94 if (_.isArray(first)) {
95 if (first.length === 2) {
96 temp = data.map((a) => ({
101 throw new Error('Wrong array format: [string, any][]');
108 _makePairsFromObject(data: object) {
109 return Object.keys(data).map((k) => ({
115 _insertFlattenObjects(temp: any[]) {
116 temp.forEach((v, i) => {
117 if (_.isPlainObject(v.value)) {
119 this._makePairs(v.value).forEach((item) => {
120 if (this.appendParentKey) {
121 item.key = v.key + ' ' + item.key;
123 temp.splice(i, 0, item);
131 _convertValue(v: any) {
132 if (_.isArray(v.value)) {
134 .map((item) => (_.isPlainObject(item) ? JSON.stringify(item) : item))
136 } else if (_.isPlainObject(v.value) && !this.renderObjects) {
143 // Forward event triggered by the 'cd-table' datatable.
144 this.fetchData.emit();