0

I have a page with a dropdown and a ngx-datatable.

I page loads the dropdown and the table and depending on what the user selects, the table loads the relevant data.

Problem I'm having is the table is loading, but isn't showing the columns/rows, but it does have a count of how many things it should be showing which is odd.

Relevant code:

  @ViewChild(DatatableComponent) table: DatatableComponent;
  columns = [];
  rows = [];

  // The dropdown kicks off a service call which is passed to this
  loadTableData(serviceCall: Observable<any>) {
    serviceCall.subscribe(data => {
      if (data.length === 0 || !data) {
        return;
      }
      this.setColumns(data[0]);
      data.forEach(rowData => {
        this.rows.push(rowData);
      });
    });
  }

  setColumns(dataObj: object) {
    Object.keys(dataObj).forEach(key => {
      this.columns.push(key);
    });
  }

And the html for the datatable:

<ngx-datatable #table 
  class="material"
  [columns]="columns"
  [columnMode]="'force'"
  [scrollbarH]="true"
  [headerHeight]="50"
  [footerHeight]="50"
  [rowHeight]="'auto'"
  [limit]="5"
  [rows]="rows">
</ngx-datatable>

I logged the rows/columns and they both have the right data. I think it's something to do with that table loading in first, and then me trying to fill it with data.

The data structure from the service is similar to (with a lot more rows):

[
 {'id': '1', 'name': 'Joe', 'job': 'window washer'},
 {'id': '2', 'name': 'Bob', 'job': 'fireman'}
]
canpan14
  • 1,181
  • 1
  • 14
  • 36

1 Answers1

1

Leaving this up because I realized I didn't read their example code closely enough and was being dumb. Couple of problems here that I fixed:

  1. I was defining the columns wrong, it takes in a list of objects with each one having the key 'name' and it's value being the column name
  2. You can't push onto the rows/columns like I was, need to set them all at once otherwise it doesn't load that data

Fixed setColumns:

  setColumns(dataObj: object) {
    this.columns = Object.keys(dataObj).map(name => {
      return { name };
    });
  }

Fixed setting the rows:

  loadTableData(serviceCall: Observable<any>) {
    serviceCall.subscribe(data => {
      if (data.length === 0 || !data) {
        return;
      }
      this.setColumns(data[0]);
      this.rows = data;
    });
  }
canpan14
  • 1,181
  • 1
  • 14
  • 36