Alon
Alon

Reputation: 11905

Show data from the server in ag-grid

I use ag-grid in my Angular 4 project.

I bring the data from the server and then try to display it in a table, but the table remains empty (although the data exists).

Just to be sure where the problem is, I have an *ngFor which generates the same data and I can see it displayed on the screen.

I also manage to display the data in the ag-grid if I write it manually (hard-coded) and it's parsed when the page is loaded, without any ajax request.

html:

<div style="width: 200px;">
  <ag-grid-angular #agGrid style="width: 100%; height: 200px;" class="ag-fresh"
                   [gridOptions]="gridOptions">
  </ag-grid-angular>
</div>


<table class="table">
  <tr>
    <th>
      Foo
    </th>
    <th>
      Bar
    </th>
  </tr>
  <tr *ngFor="let item of gridOptions.rowData; let myIndex = index">
    <td>
      {{item.foo}}
    </td>
    <td>
      {{item.bar}}
    </td>
  </tr>
</table>

ts:

export class HomeComponent implements OnInit {
private gridOptions: GridOptions;

constructor(
  private adsService: AdsService
) {
  this.gridOptions = {};

  this.gridOptions.columnDefs = [
    {
      headerName: "Foo",
      field: "foo",
      width: 100
    },
    {
      headerName: "Bar",
      field: "bar",
      width: 100
    },
  ];

  this.gridOptions.rowData = [];
}

  ngOnInit(){
    this.myService
       .getAll()
       .subscribe(item => this.gridOptions.rowData = item);
  }
}

So I probably need to somehow let ag-grid know that the data has changed, I just don't know how to do it.

Upvotes: 3

Views: 1108

Answers (1)

trungvose
trungvose

Reputation: 20034

Working plunker: https://embed.plnkr.co/HJd1xI/

Instead of passing the gridOptions to the template, I ended up with passing separated columnRefs and rowData as below.

full-width-renderer.component.html

<ag-grid-angular #agGrid style="width: 100%; height: 350px;" class="ag-fresh"
             [gridOptions]="gridOptions"
             [columnDefs]="columnDefs"
             [rowData]="rowData">
</ag-grid-angular>

And on the component, I assign the value to rowData directly.

full-width-renderer.component.ts

this.createRowData().subscribe((result) => {
    this.rowData = result;
});

Reference

Upvotes: 3

Related Questions