Infinite row model in ag-Grid with angular, Infinite scrolling and Paging in Infinite Row Model ag-Grid.

Hello folks, Today we will learn, How we can use Infinite row model in ag-Grid. If you do not know about the models in ag-Grid then click here to check my article on it. Today will learn

  • ✔ How to use Infinite row model to increase the performance of application.

  • ✔ How to create a infinite scrolling (Server Side Infinite Scrolling).

  • ✔ How to do pagination (Server Side Paging).


Prerequisites: 
  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Set up of angular environment.

Here i am working on Angular Version 10 project.

Now follow the below steps.

Step 1: Install the ag-Grid package.
Use the below command to install the package.

npm install --save ag-grid-community ag-grid-angular


Step 2: Add the ag-Grid angular module.
Go to src/app/app.module.ts file and then add module in it as show in below snapshot.

AgGridModule.withComponents([])


Step 3: Add ag-Grid style files.
Go to Style.css file and add below files in it. (Here i am using CSS)

@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";


Step 4: Create a service to fetch the data.

Step 4.1: Here i am creating a new service to fetch the data..

ng g s FOLDER_NAME/SERVICE_NAME


Step 4.2: Let's create a function to fetch the data. Here we are fetching the data from remote server. I have local OData API of currency master.

getAllCurrency(queryString: string = null): Observable<object> {
    let url = 'http://localhost:4200/odata/currency';
    if (queryString) {
      url += `?${queryString}`;
    }
    return this.http.get(url);
  }


Note: if you know about Odata queries then you can easily understand this one.

Step 4.3: Add Http module in app.component.ts file.

HttpClientModule


Step 5: Now configure the grid.
Go to .TS file of the component in which you want to apply grid. Here i am going to app.component.ts file and add the below code as show in snapshot.

  columnDefs = [
    { headerName: 'Name', field: 'Name' },
    { headerName: 'Code', field: 'Code' },
    { headerName: 'Ex Rate', field: 'ExchangeRate' }
  ];
  grid: GridApi;
  gridOptions: GridOptions;
  rowData: any;

  constructor(
    private dataService: DataService,
  ) { }

  ngOnInit(): void {
    // SETTING THE GRID OPTION
    this.setGridOptions();
  }

  onGridReady(params: GridOptions): void {
    this.grid = params.api;
    this.grid.sizeColumnsToFit();
    let dataSourceVar: IDatasource;
    dataSourceVar = {
      getRows: (rowParams: IGetRowsParams) => {
        const pagingParams = `$top=${rowParams.endRow - rowParams.startRow}&$skip=${rowParams.startRow}`;
        const countParam = `$count=true`;
        const queryString = `${pagingParams}&${countParam}`;
        this.dataService.getAllCurrency(queryString).subscribe((data: any) => {
          // data['@odata.count'] : Show the Total Number of records in our table
          // data.value : give the records
          console.log(data);
          this.rowData = data.value;
          rowParams.successCallback(data.value, data['@odata.count']);
        });
      }
    };
    params.api.setDatasource(dataSourceVar);
  }

  setGridOptions(): void {
    this.gridOptions = {
      rowData: this.rowData,
      columnDefs: this.columnDefs,
      cacheBlockSize: 20,
      rowModelType: 'infinite',
      suppressHorizontalScroll: true,
    };
  }



Here we are using GridOptions to bind the data. GridOption is a 'one stop shop' for the entire interface into the grid.
In Gridoptions, we defined multiple options like:
rowData: used to bind the data.
columnDefs:  where we define the column's information.
rowModelType: define the name of model which we are using. Here we using infinite row model.
suppressHorizontalScroll: used to remove the horizontal scroll in ag-Grid.
cacheBlockSize: define the rows, how many rows's data we fetch from the server. Here i am fetching 20 records in a one API call.

Step 6: Add ag-Grid definiiton.
Go to .HTML file of that component and add below code.

<ag-grid-angular style="height:500px" class="ag-theme-alpine" (gridReady)="onGridReady($event)"
    [gridOptions]="gridOptions" >
</ag-grid-angular>

After follow all the steps, when we run the application, we can see the data in grid. 
This is Server Side Infinite Scroll feature in the ag-Grid. Here we are fetching only 20 records. when user scroll down the grid, then it will again hit the API and fetch more records. 

It is used to increase the performance of our application.

Paging in infinite scroll model:

If the requirement is to apply pagination instaed of infinite scroll then you have to add just two property in the Gridoptions.
pagination: set it's value true.
paginationPageSize: set the page size.

Here i am also changing the value of cacheBlockSize. It's value should be same as page size.
After run the application, it will looks like 



Hope it's helps you to learn about it.

Keep learning , Keep Growing, Keep sharing !!!


3 comments:

Jake Mathews said...

"Thanks for sharing such a great post. It is very useful and informative. Valuable information you have shared. Also, check out
Multi-Factor Authentication
MFA
Two Factor Authentication"

Anonymous said...

Thanks, this was very helpful as the ag grid documentation is really confusing

Anonymous said...

Found some issues in this approach, we cant set row height or neither ag grid handles the row grid height