0

The server API returns data in the following form:

export interface Response {
  cols: string[];
  rows: string[][];
}

cols array contains header names, while the each element of rows is an array containing some values, so the example of the response looks like this: server response example

I need to build the PrimeNG DataTable using received data, but in the documentation there is no such example. How do I do this?

1 Answer 1

2

Imagine you fetched data from your backend like that :

this.backendData = {
    cols:['name', 'Income last year'],
    rows:[['Lionbridge', 150250], ['Locatech', 1085]]
}

First, you have to create PrimeNG columns dynamically from these backend data :

this.cols = [];
var i, row, obj;
for(i=0;i<this.backendData.cols.length;i++) {
    this.cols.push(this.constructColumn(this.backendData.cols[i]));
}

Then, you have to fill the data for the PrimeNG datatable like that (by iterating on each row of backend rows data) :

this.data = [];
for(row=0;row<this.backendData.rows.length;row++) {
    obj = {};
    for(i=0;i<this.backendData.cols.length;i++) {
        obj[this.backendData.cols[i]] = this.backendData.rows[row][i];
    }
    this.data.push(obj);
}

Finally, just associate that data to the view :

<p-dataTable [value]="data">
  <p-column *ngFor="let col of cols" [field]="col.field" [header]="col.header"></p-column>
</p-dataTable>

Here is a working Plunker

Is that ok for you ?

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Thank you a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.