3
votes

I'm attempting to use ag-grid with server side pagination. I updated the code sample from the ag-grid website ( below ). I retrieve the columnDefs in the ngOnInit method but alas neither the columnHeaders appear nor the rowdata. I can debug into the GetRows function and see that the rows are coming back. The total number of records gets set correctly.

If anyone can see why the grid's not showing the columns/rows I'd really appreciate it.

This is the output in the console. ag-Grid.RowNodeBlockLoader: printCacheStatus: activePageLoadsCount = 0, blocks = {"0":{"blockNumber":0,"startRow":0,"endRow":10,"pageStatus":"loaded"}} ag-Grid.RowNodeBlockLoader: checkBlockToLoad: no pages to load ag-Grid.InfiniteCache: onPageLoaded: page = 0, lastRow = 5

but while the total number of records is returned from the call and sets

import { Component, OnInit, Input } from '@angular/core';
import {TableMetadata} from "../model/table-metadata";
import { HttpClient } from "@angular/common/http";
import { GridOptions } from "ag-grid";
import { BrxTableService } from '../service/brx-table.service';

@Component({
  selector: 'app-brx-delta-agrid',
  // templateUrl: './brx-delta-agrid.component.html',
  template: `<ag-grid-angular
    #agGrid
    style="width: 100%; height: 100%;"
    id="myGrid"
    class="ag-theme-balham"
    [columnDefs]="columnDefs"
    [components]="components"
    [floatingFilter]="true"
    [debug]="true"
    [enableServerSideSorting]="true"
    [enableServerSideFilter]="true"
    [enableColResize]="true"
    [rowSelection]="rowSelection"
    [rowDeselection]="true"
    [rowModelType]="rowModelType"
    [paginationPageSize]="paginationPageSize"
    [cacheOverflowSize]="cacheOverflowSize"
    [maxConcurrentDatasourceRequests]="maxConcurrentDatasourceRequests"
    [infiniteInitialRowCount]="infiniteInitialRowCount"
    [maxBlocksInCache]="maxBlocksInCache"
    [pagination]="true"
    [cacheBlockSize]="cacheBlockSize"
    [getRowNodeId]="getRowNodeId"
    (gridReady)="onGridReady($event)"
    ></ag-grid-angular>
`,
  styleUrls: ['./brx-delta-agrid.component.css'],
  providers: [BrxTableService]
})
export class BrxDeltaAgridComponent implements OnInit{

  public state = {
    skip: 0,
    take: 5
  };


  private columnDefs = [];
  private gridApi;
  private gridColumnApi;

  private components;
  private rowSelection;
  private rowModelType;
  private paginationPageSize;
  private cacheBlockSize;
  private cacheOverflowSize;
  private maxConcurrentDatasourceRequests;
  private infiniteInitialRowCount;
  private maxBlocksInCache;
  private getRowNodeId;


  @Input('tableMetadata') tableMetadata:TableMetadata;

  constructor(private http: HttpClient, private brxTableService:BrxTableService) {

    this.components = {
      loadingRenderer: function(params) {
        if (params.value !== undefined) {
          return params.value;
        } else {
          return '<img src="../assets/loading.gif">';
        }
      }
    };
    this.rowSelection = "multiple";
    this.rowModelType = "infinite";
    this.paginationPageSize = 10;
    this.cacheBlockSize = 10;
    this.cacheOverflowSize = 2;
    this.maxConcurrentDatasourceRequests = 2;
    this.infiniteInitialRowCount = 1;
    this.maxBlocksInCache = 2;
    this.getRowNodeId = function(item) {
      return item.R_ID;
    };
  }

  ngOnInit() {
    this.columnDefs = this.getColumnDefs();

  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    this.http
      .get("http://localhost:8080/api/"+ this.tableMetadata.tableName)
      .subscribe(data => {
        data._embedded[this.tableMetadata.tableName +"s"].forEach(function(data, index) {
          data.R_ID = "R" + (index + 1);
        });
        var dataSource = {
          rowCount: null,
          getRows: function(params) {
            console.log("asking ford " + params.startRow + " to " + params.endRow);
            setTimeout(function() {

              let collectionName ='';
              for (var property in data._embedded) {
                if (property.startsWith("BRX")) {
                  collectionName = property;
                }
              }
              var dataAfterSortingAndFiltering = sortAndFilter(data._embedded[collectionName], params.sortModel, params.filterModel);
              var rowsThisPage = dataAfterSortingAndFiltering.slice(params.startRow, params.endRow);
              var lastRow = 5; // data.page.totalElements;
              // if (dataAfterSortingAndFiltering.length <= params.endRow) {
              //   lastRow = dataAfterSortingAndFiltering.length;
              // }
              params.successCallback(rowsThisPage, lastRow);
            }, 500 );
          }
        };
        params.api.setDatasource(dataSource);
      });
  }

  public getColumnDefs() {

    let columnDefs = [];
    for (let i=0; i<this.tableMetadata.columnNames.length; i++) {
      let columnName = this.tableMetadata.columnNames[i];
      let columnDef = {
        headerName: columnName,
        field: columnName,
        width:100
      };

      columnDefs.push(columnDef);
    }

    return columnDefs;
  }
}

function sortAndFilter(allOfTheData, sortModel, filterModel) {
  return sortData(sortModel, filterData(filterModel, allOfTheData));
}
function sortData(sortModel, data) {
  var sortPresent = sortModel && sortModel.length > 0;
  if (!sortPresent) {
    return data;
  }
  var resultOfSort = data.slice();
  resultOfSort.sort(function(a, b) {
    for (var k = 0; k < sortModel.length; k++) {
      var sortColModel = sortModel[k];
      var valueA = a[sortColModel.colId];
      var valueB = b[sortColModel.colId];
      if (valueA == valueB) {
        continue;
      }
      var sortDirection = sortColModel.sort === "asc" ? 1 : -1;
      if (valueA > valueB) {
        return sortDirection;
      } else {
        return sortDirection * -1;
      }
    }
    return 0;
  });
  return resultOfSort;
}
function filterData(filterModel, data) {
  var filterPresent = filterModel && Object.keys(filterModel).length > 0;
  if (!filterPresent) {
    return data;
  }
  var resultOfFilter = [];
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    if (filterModel.age) {
      var age = item.age;
      var allowedAge = parseInt(filterModel.age.filter);
      if (filterModel.age.type == "equals") {
        if (age !== allowedAge) {
          continue;
        }
      } else if (filterModel.age.type == "lessThan") {
        if (age >= allowedAge) {
          continue;
        }
      } else {
        if (age <= allowedAge) {
          continue;
        }
      }
    }
    if (filterModel.year) {
      if (filterModel.year.values.indexOf(item.year.toString()) < 0) {
        continue;
      }
    }
    if (filterModel.country) {
      if (filterModel.country.values.indexOf(item.country) < 0) {
        continue;
      }
    }
    resultOfFilter.push(item);
  }
  return resultOfFilter;
}
1

1 Answers

2
votes
style="width: 100%; height: 100%;"

Hi folks, facepalm time... The height here was set to 100%. The table was located in an overlay that had a width of zero at the time of rendering so the rows and column headers never rendered.

I still can't get continuous server requests happening with the pagination but at least i can see the data :)

Hope this example helps someone because I couldn't find many examples online.

Thanks, Mark.