Data parser
Angular Bootstrap 5 Data parser plugin
Data Parser is a TypeScript plugin which helps to display your data (.json, .csv) in MDB5 components.
It comes with a parse()
method which can transform your data based on selected
options into the required format and set of useful functions for more complicated data
operations.
Note: Read the API tab to find all available options and advanced customization
Datatable
CSV
When parsing CSV into Datatables format (rows and columns), by default all lines are treated
as rows (there is no header included). You can change that by setting
headerIndex
to the position of a header row.
You can customize both columns and rows (values between start/end or only selected indexes).
Note: When you set a headerIndex
, remember to exclude this
value from rows (for example by setting rows.start
to a next index).
Data used in this example: Population Figures
<div class="datatable mt-4">
<table
class="table datatable-table"
mdbTable
mdbTableSort
#table="mdbTable"
#sort="mdbTableSort"
[dataSource]="dataSource"
[pagination]="pagination"
[sort]="sort"
>
<thead class="datatable-header">
<tr>
<th
*ngFor="let header of headers"
[mdbTableSortHeader]="header.field"
scope="col"
>
{{ header.label | titlecase }}
</th>
</tr>
</thead>
<tbody class="datatable-body">
<tr *ngFor="let data of table.data" scope="row">
<td>{{ data.country }}</td>
<td>{{ data.countryCode }}</td>
<td>{{ data.population2015 }}</td>
<td>{{ data.population2016 }}</td>
</tr>
</tbody>
</table>
<mdb-table-pagination #pagination></mdb-table-pagination>
</div>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
export interface CountryData {
country: string;
countryCode: string;
population2015: number;
population2016: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
dataSource: CountryData[] = [];
headers: any[] = [
{ label: 'Country', field: 'country' },
{ label: 'Code', field: 'countryCode' },
{ label: 'Population 2015', field: 'population2015' },
{ label: 'Population 2016', field: 'population2016' },
];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http
.get('assets/data.csv', { responseType: 'text' })
.subscribe((data) => {
const dataParser = this._dataParserService.useDatatableParser('csv', {
rows: { start: 10, end: 14 },
columns: {
indexes: [0, 1, 57, 58],
},
});
const { rows } = dataParser.parse(data);
const mappedRows: CountryData[] = rows.map((row) => {
return {
country: row[0],
countryCode: row[1],
population2015: row[2],
population2016: row[3],
};
});
this.dataSource = [...mappedRows];
});
}
}
JSON
You can define options for rows
in exactly the same way as in CSV format
(start, end / indexes). Instead of doing the same for columns, provide an array of selected
keys to the keys
options.
Data used in this example: Population Figures
<section class="border p-4 mb-4">
<div class="datatable mt-4">
<table
class="table datatable-table"
mdbTable
mdbTableSort
#table="mdbTable"
#sort="mdbTableSort"
[dataSource]="dataSource"
[pagination]="pagination"
[sort]="sort"
>
<thead class="datatable-header">
<tr>
<th
*ngFor="let header of headers"
[mdbTableSortHeader]="header.field"
scope="col"
>
{{ header.label | titlecase }}
</th>
</tr>
</thead>
<tbody class="datatable-body">
<tr *ngFor="let data of table.data" scope="row">
<td>{{ data.country }}</td>
<td>{{ data.countryCode }}</td>
<td>{{ data.population2015 }}</td>
<td>{{ data.population2016 }}</td>
</tr>
</tbody>
<mdb-table-pagination #pagination></mdb-table-pagination>
</div>
</section>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
export interface CountryData {
country: string;
countryCode: string;
population2015: number;
population2016: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
dataKeys: string[] = ['Country', 'Country_Code', 'Year_2015', 'Year_2016'];
dataSource: CountryData[] = [];
headers: any[] = [
{ label: 'Country', field: 'country' },
{ label: 'Code', field: 'countryCode' },
{ label: 'Population 2015', field: 'population2015' },
{ label: 'Population 2016', field: 'population2016' },
];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data.json').subscribe((data) => {
const dataParser = this._dataParserService.useDatatableParser('json', {
rows: { start: 30, end: 100 },
keys: this.dataKeys,
});
const { rows } = dataParser.parse(data);
const mappedRows: CountryData[] = rows.map((item) => {
return {
country: item[`${this.dataKeys[0]}`],
countryCode: item[`${this.dataKeys[1]}`],
population2015: item[`${this.dataKeys[2]}`],
population2016: item[`${this.dataKeys[3]}`],
};
});
this.dataSource = [...mappedRows];
});
}
}
Vector Maps
CSV
Creating a colorMap based on a CSV Data requires identifying the region - Vector Maps uses alpha2Code for IDs, which isn't always convenient. Data Parser can, in most cases, fetch the required identifier based on the country's name or alpha3Code.
Note: If you don't set the step
option to a fixed value, Data
Parser will compute equal size intervals - it may resolve in empty intervals if values are
unevenly distributed.
Data used in this example: Population Figures
<mdb-vector-map
[map]="'world'"
[fill]="'#fff'"
[readonly]="false"
[hover]="false"
[colorMap]="colorMap"
></mdb-vector-map>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
colorMap: any[] = [];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http
.get('assets/data.csv', { responseType: 'text' })
.subscribe((data) => {
const dataParser = this._dataParserService.useVectorMapParser('csv', {
color: 'lightGreen',
field: 42,
rows: {
start: 1,
},
step: 8000000,
countryIdentifier: 1,
});
const { colorMap } = dataParser.parse(data);
this.colorMap = colorMap;
});
}
}
JSON
Apart from a colorMap, parse()
method returns also a legend based on which you
can easily display value-color corelations.
If you're not satisfied with colors available out of the box, you can pass an array of color strings based on which DataParser will create your colorMap.
The getCoordinates()
method helps to find x and y map coordinates based on
longitude and latitude.
Calculated point is an approximation and might not be accurate.
Data used in this example: Population Figures
Population (2016):
<section class="border p-4 mb-4" style="background-color: rgb(7 43 49)">
<div class="row m-0">
<div class="col-lg-3 border-right border-bottom border-light">
<h5 class="text-light p-3 mb-1">Population (2016):</h5>
<hr />
<ul id="legend-json" class="vector-map-legend px-3"></ul>
</div>
<div class="col-lg-9 p-0">
<mdb-vector-map
[map]="'world'"
[fill]="'rgb(7 43 49)'"
[colorMap]="colorMap"
[tooltips]="true"
[stroke]="'#fff'"
[btnClass]="'btn-light'"
[readonly]="true"
[hover]="false"
[markers]="markers"
></mdb-vector-map>
</div>
</div>
</section>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
colorMap: any[] = [];
markers: any[] = [];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data.json').subscribe((data) => {
const dataParser = this._dataParserService.useVectorMapParser('json', {
color: [
'rgba(163, 199, 210, 0.05)',
'rgba(163, 199, 210, 0.1)',
'rgba(163, 199, 210, 0.15)',
'rgba(163, 199, 210, 0.2)',
'rgba(163, 199, 210, 0.25)',
'rgba(163, 199, 210, 0.3)',
'rgba(163, 199, 210, 0.35)',
'rgba(163, 199, 210, 0.4)',
'rgba(163, 199, 210, 0.45)',
'rgba(163, 199, 210, 0.5)',
],
field: 'Year_2016',
step: 8000000,
countryIdentifier: 'Country_Code',
tooltips: (value: any) => `Population: ${value}`,
});
const legendList = document.getElementById('legend-json');
const getLegend = (legend: any[]) => {
return legend
.map((color, i) => {
let label;
if (i === 0) {
label = `< ${color.max}`;
} else if (i === legend.length - 1) {
label = `> ${color.min}`;
} else {
label = `${color.min} - ${color.max}`;
}
return `
<li class="vector-map-legend__item my-2">
<div class="vector-map-legend__color me-2 border border-light" style="background-color: ${color.color}"></div>
<small>${label}</small>
</li>
`;
})
.join('\n');
};
const { colorMap, legend } = dataParser.parse(data);
this.colorMap = colorMap;
this.markers = [
{
...dataParser.getMapCoordinates(52.107811, 19.94487),
fill: 'rgb(185, 211, 220)',
type: 'bullet',
label: 'Warsaw',
latitude: 52.2297,
longitude: 21.0122,
},
];
legendList!.innerHTML = getLegend(legend);
});
}
}
Charts
CSV
Creating datasets for your Chart component requires two kinds of labels - labels for each
specific dataset (datasetLabel
: column's index) as well as labels for data
points (labelsIndex
: index of a row with labels).
Additionally, you can format the datasetLabel
using
formatLabel
option.
Note: Data Parser generates a color for each dataset, which you can later
use for background/border color. By default, values comes from mdb
palette but
you can also use
full palette
- in this case the color
option's value should refer to the intensity (from 50
to 900).
Basic data
Suitable for most of the chart types (line, bar, horizontal bar, radar, polar, doughnut, pie)
Data used in this example: Population Figures
<canvas
mdbChart
[type]="'line'"
[datasets]="datasets"
[labels]="labels"
[options]="options"
></canvas>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
datasets: any[] = [];
labels: any[] = [];
options = {
plugins: {
tooltip: {
displayColors: false,
},
},
};
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http
.get('assets/data.csv', { responseType: 'text' })
.subscribe((data) => {
const dataParser = this._dataParserService.useChartParser('csv', {
rows: { start: 170, end: 176 },
datasetLabel: 0,
labelsIndex: 0,
formatLabel: (label) => {
return label.replace('Year_', '');
},
});
const { labels, datasets } = dataParser.parse(data);
this.labels = [...labels];
this.datasets = datasets.map((dataset: { color: any }) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
color: dataset.color,
}));
});
}
}
Coordinates
Parsing data for scatter & bubble charts
<canvas
mdbChart
[type]="'bubble'"
[datasets]="datasets"
[labels]="labels"
[options]="options"
></canvas>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
datasets: any[] = [];
labels: any[] = [];
options = {
plugins: {
tooltip: {
displayColors: false,
},
},
scales: {
x: {
title: {
display: true,
text: 'Time consumed (%)',
},
},
y: {
title: {
display: true,
text: 'Tasks done (%)',
},
},
},
};
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http
.get('assets/data-bubble.csv', { responseType: 'text' })
.subscribe((data) => {
const dataParser = this._dataParserService.useChartParser('csv', {
datasetLabel: 0,
labelsIndex: 0,
rows: {
start: 1,
},
getCoordinates: ([
departament,
done,
team,
startDate,
currentDate,
deadline,
]: any) => {
const getDayDifference = (firstDate: any, secondDate: any) => {
return (
(new Date(secondDate).getTime() -
new Date(firstDate).getTime()) /
(1000 * 3600 * 24)
);
};
const timeConsumedPercentage = Math.round(
(getDayDifference(startDate, currentDate) /
getDayDifference(startDate, deadline)) *
100
);
const targetPercentage = done * 100;
return {
x: timeConsumedPercentage,
y: targetPercentage,
r: team,
};
},
color: 400,
});
const { labels, datasets } = dataParser.parse(data);
this.labels = [...labels];
this.datasets = datasets.map((dataset: any) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
backgroundColor: dataset.color,
}));
});
}
}
departament,done,team,startDate,currentDate,deadline
Marketing,0.67,10,2019-03-01,2020-10-23,2020-12-10
Business,0.49,12,2019-01-02,2020-10-23,2020-11-30
Backend,0.88,32,2019-06-01,2020-10-23,2020-11-23
Frontend,0.79,29,2019-08-01,2020-10-23,2020-11-30
Design,0.91,7,2019-07-01,2020-10-23,2020-11-01
JSON
When working with JSON data for you Chart component, you can define which
keys
should be parsed or select all without those specified in the
ignoreKeys
options.
Basic data
Data used in this example: Population Figures
Suitable for most of the chart types (line, bar, horizontal bar, radar, polar, doughnut, pie)
<section class="border p-4" style="background-color: rgb(7 43 49)">
<canvas
mdbChart
[type]="'line'"
[datasets]="datasets"
[labels]="labels"
[options]="options"
></canvas>
</section>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
datasets: any[] = [];
labels: any[] = [];
options = {
plugins: {
tooltip: {
displayColors: false,
backgroundColor: 'rgba(255, 255, 255, 0.9)',
titleColor: 'rgb(7, 43, 49)',
bodyColor: 'rgb(7, 43, 49)',
},
},
legend: {
labels: {
color: 'rgba(255, 255, 255, 0.7)',
},
},
scales: {
x: {
ticks: {
color: 'rgba(255, 255, 255, 0.7)',
},
},
y: {
ticks: {
color: 'rgba(255, 255, 255, 0.7)',
},
grid: {
color: 'rgba(255, 255, 255, 0.3)',
},
},
},
};
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data.json').subscribe((data) => {
const dataParser = this._dataParserService.useChartParser('json', {
datasetLabel: 'Country',
ignoreKeys: ['Country', 'Country_Code'],
rows: { start: 9, end: 14 },
formatLabel: (label: string) => {
return label.replace('Year_', '');
},
color: 100,
});
const { labels, datasets } = dataParser.parse(data);
this.labels = [...labels];
this.datasets = datasets.map((dataset: any) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
color: dataset.color,
}));
});
}
}
Coordinates
Parsing data for scatter & bubble charts
<section class="border p-4 mb-4" style="background-color: rgb(7 43 49)">
<canvas
mdbChart
[type]="'bubble'"
[datasets]="datasets"
[labels]="labels"
[options]="options"
></canvas>
</section>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
datasets: any[] = [];
labels: any[] = [];
options = {
plugins: {
tooltip: {
displayColors: false,
backgroundColor: 'rgba(255, 255, 255, 0.9)',
titleColor: 'rgb(7, 43, 49)',
bodyColor: 'rgb(7, 43, 49)',
},
},
legend: {
labels: {
color: 'rgba(255, 255, 255, 0.7)',
},
},
scales: {
x: {
ticks: {
color: 'rgba(255, 255, 255, 0.7)',
},
title: {
display: true,
text: 'Time consumed (%)',
color: 'rgba(255, 255, 255, 0.7)',
},
},
y: {
ticks: {
color: 'rgba(255, 255, 255, 0.7)',
},
grid: {
color: 'rgba(255, 255, 255, 0.3)',
},
title: {
display: true,
text: 'Tasks done (%)',
color: 'rgba(255, 255, 255, 0.7)',
},
},
},
};
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data-bubble.json').subscribe((data) => {
const dataParser = this._dataParserService.useChartParser('json', {
datasetLabel: 'departament',
getCoordinates: ({
done,
team,
startDate,
currentDate,
deadline,
}: any) => {
const getDayDifference = (firstDate: any, secondDate: any) => {
return (
(new Date(secondDate).getTime() - new Date(firstDate).getTime()) /
(1000 * 3600 * 24)
);
};
const timeConsumedPercentage = Math.round(
(getDayDifference(startDate, currentDate) /
getDayDifference(startDate, deadline)) *
100
);
const targetPercentage = done * 100;
return {
x: timeConsumedPercentage,
y: targetPercentage,
r: team,
};
},
color: 100,
});
const { labels, datasets } = dataParser.parse(data);
this.labels = [...labels];
this.datasets = datasets.map((dataset: any) => ({
...dataset,
pointRadius: 0,
borderColor: dataset.color,
backgroundColor: dataset.color,
}));
});
}
}
[
{
"departament": "Marketing",
"done": 0.67,
"team": 10,
"startDate": "2019-03-01",
"currentDate": "2020-10-23",
"deadline": "2020-12-10"
},
{
"departament": "Business",
"done": 0.49,
"team": 12,
"startDate": "2019-01-02",
"currentDate": "2020-10-23",
"deadline": "2020-11-30"
},
{
"departament": "Backend",
"done": 0.88,
"team": 32,
"startDate": "2019-06-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-23"
},
{
"departament": "Frontend",
"done": 0.79,
"team": 29,
"startDate": "2019-08-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-30"
},
{
"departament": "Design",
"done": 0.91,
"team": 7,
"startDate": "2019-07-01",
"currentDate": "2020-10-23",
"deadline": "2020-11-01"
}
]
Treeview
Using the Treeview requires defining name and children properties in your objects - as it can be an inconvenience, Data Parser allows pointing to other fields as their equivalent (f.e. name -> title, children -> content).
In the same time, you can still make use of other properties (icon, disabled, show) which are not typically defined in data structures. Each of them is a function which takes an object as its argument and returns a field's value depending on your custom logic.
JSON
Note: CSV format is not available for the Treeview component.
<mdb-treeview
textField="name"
childrenField="children"
[nodes]="data"
></mdb-treeview>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
data: any[] = [];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data-treeview.json').subscribe((data) => {
const expandFolder = ({ name }: { name: string }): boolean => {
const expandedFolders = ['Desktop', 'Programming', 'node_modules'];
return expandedFolders.includes(name);
};
const dataParser = this._dataParserService.useTreeviewParser({
show: expandFolder,
children: 'content',
name: (el: { directory: any; name: any; extension: any }) => {
const name = el.directory ? el.name : `${el.name}.${el.extension}`;
return name;
},
icon: (el: any) => {
const getExtensionIcon = (extension: string) => {
const iconMap: { [key: string]: string } = {
doc: 'file-alt',
js: 'file-code',
zip: 'file-archive',
webp: 'file-image',
pdf: 'file-pdf',
};
return iconMap[extension] || 'file';
};
const icon = el.directory
? 'folder-closed'
: getExtensionIcon(el.extension);
return `far fa-${icon} mx-2`;
},
});
this.data = dataParser.parse(data);
});
}
}
[
{
"name": "Desktop",
"directory": true,
"content": [
{
"name": "Programming",
"directory": true,
"content": [
{
"name": "index",
"extension": "js"
},
{
"name": "README",
"extension": "md"
},
{
"name": "package",
"extension": "json"
},
{
"name": "node_modules",
"directory": true,
"content": [
{
"name": "mdb-ui-kit",
"directory": true
}
]
}
]
},
{
"name": "avatar",
"extension": "webp"
}
]
},
{
"name": "Downloads",
"directory": true,
"content": [
{
"name": "lectures",
"extension": "zip"
},
{
"name": "school-trip",
"extension": "zip"
},
{
"name": "physics-assignment",
"extension": "pdf"
},
{
"name": "presentation",
"extension": "pdf"
},
{
"name": "wallpaper",
"extension": "webp"
}
]
},
{
"name": "Documents",
"directory": true,
"content": [
{
"name": "Homework",
"directory": true,
"content": [
{
"name": "maths",
"extension": "doc"
},
{
"name": "english",
"extension": "doc"
},
{
"name": "biology",
"extension": "doc"
},
{
"name": "computer-science",
"extension": "js"
}
]
}
]
},
{
"name": "Pictures",
"directory": true,
"content": [
{
"name": "Holiday",
"directory": true,
"content": [
{
"name": "1",
"extension": "webp"
},
{
"name": "2",
"extension": "webp"
},
{
"name": "3",
"extension": "webp"
},
{
"name": "4",
"extension": "webp"
}
]
},
{
"name": "School trip",
"directory": true,
"content": [
{
"name": "ABD001",
"extension": "webp"
},
{
"name": "ADB002",
"extension": "webp"
},
{
"name": "ADB004",
"extension": "webp"
},
{
"name": "ADB005",
"extension": "webp"
}
]
}
]
}
]
Data parser - API
Installation
To install and configure the plugin follow our Plugins Installation Guide. Please remember to update all the plugin names and import paths. You can find all the necessary information in the Import section.
npm i git+https://oauth2:ACCESS_TOKEN@git.mdbootstrap.com/mdb/angular/mdb5/plugins/prd/data-parser
Import
import { MdbDataParserService } from 'mdb-angular-data-parser';
…
@NgModule ({
...
providers: [MdbDataParserService],
...
})
Methods
Name | Description | Example |
---|---|---|
useDatatableParser(format:MdbDataParserFormat, options?: MdbDataParserDatatableOptions) |
Returns parser object for Datatable component | _dataParserService.useDatatableParser('csv', options) |
useVectorMapParser(format:MdbDataParserFormat, options?: MdbDataParserVectorMapOptions) |
Returns parser object for Vector Maps plugin | _dataParserService.useVectorMapParser('csv', options) |
useChartParser(format:MdbDataParserFormat, options?:MdbDataParserChartOptions) |
Returns parser object for Chart component | _dataParserService.useChartParser('csv', options) |
useTreeviewParser(options?:MdbDataParserTreeviewOptions) |
Returns parser object for Treeview plugin | _dataParserService.useTreeviewParser(options) |
<div class="datatable mt-4">
<table
class="table datatable-table"
mdbTable
mdbTableSort
#table="mdbTable"
#sort="mdbTableSort"
[dataSource]="dataSource"
[pagination]="pagination"
[sort]="sort"
>
<thead class="datatable-header">
<tr>
<th
*ngFor="let header of headers"
[mdbTableSortHeader]="header.field"
scope="col"
>
{{ header.label | titlecase }}
</th>
</tr>
</thead>
<tbody class="datatable-body">
<tr *ngFor="let data of table.data" scope="row">
<td>{{ data.country }}</td>
<td>{{ data.countryCode }}</td>
<td>{{ data.population2015 }}</td>
<td>{{ data.population2016 }}</td>
</tr>
</tbody>
</table>
<mdb-table-pagination #pagination></mdb-table-pagination>
</div>
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
export interface CountryData {
country: string;
countryCode: string;
population2015: number;
population2016: number;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
dataSource: CountryData[] = [];
headers: any[] = [
{ label: 'Country', field: 'country' },
{ label: 'Code', field: 'countryCode' },
{ label: 'Population 2015', field: 'population2015' },
{ label: 'Population 2016', field: 'population2016' },
];
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http
.get('assets/data.csv', { responseType: 'text' })
.subscribe((data) => {
const dataParser = this._dataParserService.useDatatableParser('csv', {
rows: { start: 10, end: 14 },
columns: {
indexes: [0, 1, 57, 58],
},
});
const { rows } = dataParser.parse(data);
const mappedRows: CountryData[] = rows.map((row) => {
return {
country: row[0],
countryCode: row[1],
population2015: row[2],
population2016: row[3],
};
});
this.dataSource = [...mappedRows];
});
}
}
Options
Methods accepts one or two arguments:
Name | Type | Default | Description |
---|---|---|---|
format |
String | 'json' |
Available values: csv, json |
options
|
Object |
|
Available options depend on selected strategy |
Datatable
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
columns
|
Object | { start: 0 } |
Defines which columns should be parsed - either with start/end values or an array of indexes. |
columns.start
|
Number | 0 |
Index of the first data column |
columns.end
|
Number |
|
Index of the last data column (when undefined it will be the last available index) |
columns.indexes
|
Array |
|
Set of column indexes to parse |
headerIndex
|
Number | -1 |
Index of the line containing headers (f.e. when set to 0, rows.start should be 1) |
delimiter
|
String | , |
Character separating values in a file |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
keys
|
Array |
|
Array of keys (columns) to parse (by default all) |
Methods
Name | Description | Example |
---|---|---|
parse(data: CSV/JSON) |
Returns data parsed into the format required by the component | dataParser.parse(csvData) |
getValueExtrema(data: CSV/JSON, field:string|number) |
Returns maximum and minimum values in a column | dataParser.getValueExtrema(csvData, 3) |
Vector Maps
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
headerIndex
|
Number | -1 |
Index of a line containing headers (if set, rows' start should be moved to the next index) |
delimiter
|
String | , |
Character separating values in a file |
color
|
String, Array | 'blue' |
Name of the color palette (see more in section below) or an array of custom colors |
field
|
Number |
|
Index of a value based on which a region should be colored |
countryIdentifier
|
Number |
|
Index of a field containing country identifier (alpha2code, alpha3code, country's name) |
countries
|
Array |
|
Array of identifiers - if defined, only those countries will appear in the colorMap |
tooltips
|
Function |
|
Allows generating custom tooltips |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
color
|
String, Array | 'blue' |
Name of the color palette (see more in section below) or an array of custom colors |
field
|
String |
|
Key based on which a region should be colored |
countryIdentifier
|
String |
|
Key containing country identifier (alpha2code, alpha3code, country's name) |
countries
|
Array |
|
Array of identifiers - if set, only those countries will appear in the colorMap |
tooltips
|
Function |
|
Allows generating custom tooltips |
Color maps
Choose one of the colors from our full palette for your color map:
red
pink
purple
deepPurple
indigo
lightBlue
cyan
teal
green
lightGreen
lime
yellow
amber
orange
deepOrange
gray
blueGray
Methods
Name | Description | Example |
---|---|---|
parse(data: CSV/JSON) |
Returns data parsed into the format required by the component | dataParser.parse(csvData) |
getValueExtrema(data: CSV/JSON, field:string|number) |
Returns maximum and minimum values in a column | dataParser.getValueExtrema(csvData, 3) |
getIdentifiers(data: CSV/JSON) |
Returns an array of strings representing the identifiers (country codes) | dataParser.getIdentifiers(csvData) |
getMapCoordinates(latitude:number, longitude:number) |
Returns an object with two properties: x and y, representing the x and y coordinates on a map corresponding to the input latitude and longitude | dataParser.getMapCoordinates(52.107811, 19.94487) |
Charts
CSV options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
columns
|
Object | { start: 0 } |
Defines which columns should be parsed - either with start/end values or an array of indexes. |
columns.start
|
Number | 0 |
Index of the first data column |
columns.end
|
Number |
|
Index of the last data column (when undefined it will be the last available index) |
columns.indexes
|
Array |
|
Set of column indexes to parse |
datasetLabel
|
Number |
|
Index of a value in each entry which should be treated as a label for a dataset |
delimiter
|
String | , |
Character separating values in a file |
labelsIndex
|
Number | -1 |
Index of a row in .csv file containing value labels |
formatLabel
|
Function | (label) => label |
Function formatting labels (per value, not dataset) |
color
|
String | mdb |
Color palette from which values will be assigned to datasets |
getCoordinates
|
function |
|
Function which takes an entry as its parameter and should return an object with coordinates (bubble, scatter chart) |
JSON options
Name | Type | Default | Description |
---|---|---|---|
rows
|
Object | { start: 0 } |
Defines which rows should be parsed - either with start/end values or an array of indexes. |
rows.start
|
Number | 0 |
Index of the first data row |
rows.end
|
Number |
|
Index of the last data row (when undefined it will be the last available index) |
rows.indexes
|
Array |
|
Set of row's indexes to parse |
keys
|
Array |
|
Set of keys which should be parsed |
ignoreKeys
|
Array | [] |
Set of keys which should be ignored when parsing |
datasetLabel
|
String |
|
Key which value should be treated as a label for a dataset |
formatLabel
|
Function | (label) => label |
Function formatting labels (per value, not dataset) |
color
|
String | mdb |
Color palette from which values will be assigned to datasets |
getCoordinates
|
function |
|
Function which takes an entry as its parameter and should return an object with coordinates (bubble, scatter chart) |
Colors
Setting the color
attribute to 'mdb'
will assign one of MDB
theme
colors
to each dataset (primary, secondary), while using a number value will iterate through entire
color palette
for given intensity (50, 100, ... 900).
Available values:
mdb
50
100
200
300
400
500
600
700
800
900
Methods
Name | Description | Example |
---|---|---|
parse(data: CSV/JSON) |
Returns data parsed into the format required by the component | dataParser.parse(csvData) |
getValueExtrema(data: CSV/JSON, field:string|number) |
Returns maximum and minimum values in a column | dataParser.getValueExtrema(csvData, 3) |
Treeview
JSON options
Name | Type | Default | Description |
---|---|---|---|
name
|
String / Function | 'name' |
Reference to the JSON fields that should be a 'name' Treeview structure parameter for items |
children
|
String | 'children' |
Reference to the JSON fields that should be a 'children' Treeview structure parameter for items |
icon
|
String / Function / null | 'null' |
Reference to the JSON fields that should be an 'icon' Treeview structure parameter for items |
show
|
Function / Boolean | 'false' |
Reference to the JSON fields or a static value that should be a 'show' Treeview structure parameter for items |
disabled
|
Function / Boolean | 'false' |
Reference to the JSON fields or a static value that should be a 'disabled' Treeview structure parameter for items |
id
|
String / Number / null | 'null' |
Reference to the JSON fields or a static value that should be an 'id' Treeview structure parameter for items |
Methods
Name | Description | Example |
---|---|---|
parse(data: CSV/JSON) |
Returns data parsed into the format required by the component | dataParser.parse(csvData) |
Util functions
Arrays
flattenDeep(array)
Flattens a multi-level array into single-level one.
this._dataParserService.flattenDeep([1, [2, [3, [4]], 5]]);
// output: [1, 2, 3, 4, 5]
pullAll(array, array)
Pulls particular elements from an array.
this._dataParserService.pullAll(['a', 'b', 'c', 'a', 'b', 'c'], ['a', 'c']);
// output: ['b', 'b']
take(array, number)
Returns a particular amount of items from the start of an array.
this._dataParserService.take([1, 2, 3, 4, 5], 2);
// output: [1, 2]
takeRight(array, number)
Returns a particular amount of items from the end of an array.
this._dataParserService.takeRight([1, 2, 3, 4, 5], 2);
// output: [4, 5]
union(set of arrays)
Concatenates many arrays into one, single-level and removes duplicates.
this._dataParserService.union([1, 2], [3, ['four', [5]]], ['six']);
// output: [1, 2, 3, 'four', 5, 'six']
unionBy(function / string, set of arrays / objects)
Concatenates many arrays into one, single-level by particular criterium and removes duplicates.
this._dataParserService.unionBy(Math.floor, [2.1], [1.2, 2.3]);
// output: [2.1, 1.2]
uniq(array)
Returns an array without duplicates.
this._dataParserService.uniq([1, 2, 1, 3]);
// output: [1, 2, 3]
uniqBy(function / string, array / object)
Returns an array without duplicates set by a particular criterium.
this._dataParserService.uniqBy(Math.floor, [2.1, 1.2, 2.3]);
// output: [2.1, 1.2]
zip(arrays)
Zips first items of a set of arrays into one array, second ones into second and so on.
this._dataParserService.zip(['a', 'b'], [1, 2], [true, false]);
// output: [['a', 1, true], ['b', 2, false]]
zipObject(array, array)
Creates an object with keys from the first array and values from the second one.
this._dataParserService.zipObject(['a', 'b'], [1, 2]);
// output: { 'a': 1, 'b': 2 }
Collections
countBy(array / object, function / string)
Returns an object with values converted using the second parameter as a key and number of items that it matches as a value.
this._dataParserService.countBy([6.1, 4.2, 6.3], Math.floor);
// output: { 4: 1, 6: 2 }
this._dataParserService.countBy({ x: 'one', y: 'two', z: 'three', a: 'one' }, 'length');
// output: { 3: 3, 5: 1 }
groupBy(array / object, function / string)
Returns an object with values converted using the second parameter as a key and an array of items that it matches as a value.
this._dataParserService.groupBy([6.1, 4.2, 6.3], Math.floor);
// output: { 4: [4.2], 6: [6.1, 6.3] }
this._dataParserService.groupBy({ x: 'one', y: 'two', z: 'three', a: 'one' }, 'length');
// output: { 3: ['one', 'two', 'one'], 5: ['three'] }
sortBy(array / object, array)
Returns a sorted array by values from the second parameter.
vehicles = [
{ name: 'car', id: 1 },
{ name: 'airplane', id: 4 },
{ name: 'bike', id: 2 },
{ name: 'boat', id: 3 },
];
this._dataParserService.sortBy(this.vehicles, ['name', 'id']);
// output:
// [
// { name: 'airplane', id: 4 },
// { name: 'bike', id: 2 },
// { name: 'boat', id: 3 },
// { name: 'car', id: 1 }
// ]
orderBy(array / object, array, array)
Returns a sorted array by values from the second parameter and order from the third one.
vehicles = [
{ name: 'car', id: 1 },
{ name: 'airplane', id: 4 },
{ name: 'bike', id: 2 },
{ name: 'boat', id: 3 },
];
this._dataParserService.orderBy(this.vehicles, ['name', 'id'], ['desc', 'desc']);
// output:
// [
// { name: 'car', id: 1 },
// { name: 'boat', id: 3 },
// { name: 'bike', id: 2 },
// { name: 'airplane', id: 4 }
// ]
Objects
invert(object)
Inverts object keys with their values.
this._dataParserService.invert({ '1': 'a', '2': 'b'});
// output: {a: '1', b: '2'}
invertBy(object, function(optional))
Inverts object keys with their values and puts duplicates into the array.
this._dataParserService.invertBy({ 'a': '1', 'b': '2', 'c': '1' });
// output: { '1': ['a', 'c'], '2': ['b'] }
this._dataParserService.invertBy({ 'a': '1', 'b': '2', 'c': '1' }, (key) => `group${key}`);
// output: { 'group1': ['a', 'c'], 'group2': ['b'] }
omit(object, array / string)
Returns object without particular elements.
this._dataParserService.omit({ 'a': '1', 'b': '2', 'c': '3' }, ['a', 'c']);
// output: { 'b': '2' }
omitBy(object, function)
Returns object without particular elements that are the function result.
this._dataParserService.omitBy({ 'a': 1, 'b': '2', 'c': 3 }, (item) => typeof item !== 'number');
// output: { 'a': 1, 'c': 3 }
pick(object, array)
Returns particular elements from an object.
this._dataParserService.pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']);
// output: { 'a': 1, 'c': 3 }
pickBy(object, function)
Returns particular elements that are function result from an object.
this._dataParserService.pickBy({ 'a': 1, 'b': '2', 'c': 3 }, (item) => typeof item !== 'number');
// output: { 'b': '2' }
transform(object, function, accelerator)
Transforms object using a function parameter and accelerator as a start value.
this._dataParserService.transform(
{ a: 1, b: 2, c: 1 },
function (result, value, key) {
(result[value] || (result[value] = [])).push(key);
},
{}
);
// output: { '1': ['a', 'c'], '2': ['b'] }
More
colorGenerator(array / string / number, number (iterator))
Allows to generate colors from an array.
colorIterator = this._dataParserService.colorGenerator(
[
'#FFEBEE',
'#FCE4EC',
'#F3E5F5',
'#EDE7F6',
'#E8EAF6',
'#E3F2FD',
'#E1F5FE',
'#E0F7FA',
'#E0F2F1',
'#E8F5E9',
'#F1F8E9',
'#F9FBE7',
'#FFFDE7',
'#FFF8E1',
'#FFF3E0',
'#FBE9E7',
'#EFEBE9',
'#FAFAFA',
'#ECEFF1',
],
0
);
color = colorIterator.next().value;
color2 = colorIterator.next().value;
// 'color' variable is equal to: '#FFEBEE'
// 'color2' variable is equal to: '#FCE4EC'
// You can also use our predefined arrays:
colorIterator2 = DataParser.colorGenerator(100, 0);
color3 = colorIterator2.next().value;
// 'color3' variable is equal to: '#FFCDD2'
colorIterator3 = DataParser.colorGenerator('lightGreen', 0);
color4 = colorIterator3.next().value;
// 'color4' variable is equal to: '#F1F8E9'
getCSVDataArray(data (csv), string (delimiter))
Allows to parse a CSV data to an array.
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MdbDataParserService } from 'mdb-angular-data-parser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
constructor(
private _http: HttpClient,
private _dataParserService: MdbDataParserService
) {}
ngOnInit(): void {
this._http.get('assets/data.csv').subscribe((data) => {
const parsedData = this._dataParserService.getCSVDataArray(data, ',');
// 'parsedData' variable is equal to:
// [
// ['departament', 'done', 'team', 'startDate', 'currentDate', 'deadline'],
// ['Marketing', '0.67', '10', '2019-03-01', '2020-10-23', '2020-12-10'],
// ['Business', '0.49', '12', '2019-01-02', '2020-10-23', '2020-11-30'],
// ['Backend', '0.88','32', '2019-06-01', '2020-10-23', '2020-11-23'],
// ['Frontend', '0.79','29', '2019-08-01', '2020-10-23', '2020-11-30'],
// ['Design', '0.91', '7', '2019-07-01', '2020-10-23', '2020-11-01']
// ]
});
}
}
departament,done,team,startDate,currentDate,deadline
Marketing,0.67,10,2019-03-01,2020-10-23,2020-12-10
Business,0.49,12,2019-01-02,2020-10-23,2020-11-30
Backend,0.88,32,2019-06-01,2020-10-23,2020-11-23
Frontend,0.79,29,2019-08-01,2020-10-23,2020-11-30
Design,0.91,7,2019-07-01,2020-10-23,2020-11-01