The implementation of the data source in ag grid is not functioning

Implemented an ag-grid and configured a data source.

However, the data source is not being triggered. How can we execute the data source properly?

HTML Code:

<div class="col-md-12" *ngIf="rowData.length > 0">  
    <ag-grid-angular #agGrid style="width: 100%; height: 350px;" class="ag-fresh"
        [gridOptions]="gridOptions"
        [columnDefs]="columnDefs"    
        [rowData]="rowData"
        [datasource] = "dataSource"
        enableColResize
        enableSorting
        enableFilter
        rowSelection="single"
    ></ag-grid-angular>
</div>

Component where the grid is defined:

import { Component } from '@angular/core';
import { FormGroup, FormControl } from "@angular/forms";
import {GridOptions} from "ag-grid/main";
import {Http, Headers} from '@angular/http';
import * as AppUtils from '../common/app.utils';

@Component({ 
    selector: 'incident-search',
    templateUrl: 'app/search/iSearch.component.html'
})
export class ISearchComponent {
    myForm: FormGroup;
    rowData: Array<IncidentHeaderModel> = new Array<IncidentHeaderModel>();

    gridOptions = <GridOptions>{
        context: {},
        rowModelType: 'pagination',
        enableServerSideFilter: true,
        paginationPageSize: 10

    };
    columnDefs:any[] = [
        {headerName: 'Status', field: 'incidentStatus.value'},
            {headerName: 'Category', field: 'categoryMast.catDesc'},
            {headerName: 'Sub Category', field: 'subCategoryMast.subCatDesc'},
            {headerName: 'Location', field: 'location.locName'},
            {headerName: 'Time', field: 'incidentTime'},
            {headerName: 'Delay(Hrs)', cellRenderer:this.getDelayInHours}

        ];


        constructor(private masterDataService:MasterDataService,private http: Http) {
            this.myForm = new FormGroup({
            'catCode'   : new FormControl()

        });



        }  

        dataSource = {
           pageSize: 10,
            getRows: (params: any) => {
              console.log("here dataSource")
                    this.searchIncident(params.startRow, params.endRow); // returns json from server
                    var rowsThisPage = this.rowData;
                    var lastRow = -1;
                    if (rowsThisPage.length <= params.endRow) {
                        lastRow = rowsThisPage.length;
                    }
                  params.successCallback(rowsThisPage, lastRow);
            }
         }



    searchIncident(start:number, end:number){

      if (!start) {
            start = 1;
          }
      myJson['firstResult'] = start;
      myJson.maxResult = this.gridOptions.paginationPageSize;

       this.http.post(AppUtils.INCIDENT_SEARCH, this.myForm.value, {headers: headers}).subscribe(res=>{
              this.rowData = res.json().result;
             }, err=>{             
             });

        }
    }

When clicking on the search button in HTML, the grid does not load successfully.

searchIncident() {


Search

A warning message appears in the console: cannot call setRowData unless using normal row model

An unfinished Plunker example: http://plnkr.co/edit/qIeONaAe4INyTuZTGAOK?open=app%2Fapp.component.ts&p=preview

Answer №1

Check out this code snippet inspired by the example at this link

The dataSource features a callback function that populates the grid with data. The line of code

this.gridOptions.api.setRowData(data);
is responsible for refreshing the grid's data.

The AJAX method should return the response as it will be processed in the dataSource.getRows function.

gridOptions = <GridOptions>{
  context: {},
  rowModelType: 'pagination',
  enableServerSideSorting: true,
  paginationPageSize: 10
};
page = 1;
searchIncident(start:number, end:number){
  if (!start) {
    start = 1;
  }
  myJson['firstResult'] = start;
  myJson.maxResult = this.gridOptions.paginationPageSize;

  this.http.post(AppUtils.INCIDENT_SEARCH, this.myForm.value, {headers: headers}).subscribe(res=>{
    return res.json().result;
    }, err=>{             
    });
}
dataSource = {
  pageSize: 10,
  //overflowSize: 10,
  getRows: (params: any) => {
    let data = this.searchIncident(params.startRow, params.startRow + dataSource.pageSize); // returns json from server
    params.successCallback(data);
  }
}

private searchIncidents() {
  dataSource.getRows({
    startRow: (this.page - 1) * this.dataSource.pageSize,
    successCallback: (data: any) => {
      this.gridOptions.api.setRowData(data);
    }
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Append method in FormData is not functioning properly within Angular

I'm facing a challenge in my Angular application where I need to enable image uploads to the server. The issue arises when attempting to add a selected file to the newly created FormData object. Below is the relevant TypeScript component snippet: ima ...

Strategies for effectively conveying jQuery and Angular

I have integrated jQuery DataTable into my code. I am facing an issue with the dataTables_scrollBody class which requires me to add a custom scroll bar. This is necessary because on Linux, the touch screen functionality in Chrome is not working effectively ...

Is it possible to navigate to a different section of a webpage while also jumping to a specific id within that section seamlessly?

I'm trying to create a navbar link that will take me directly to a specific section of a page, but I'm having trouble getting it to work. Here's what I've tried: <a href="home#id" class="nav-link text on-hover"></a> Where ...

Fetching HTML files directly after building Angular (Tips for Developing Chrome Extensions)

Currently, I am in the process of creating a custom Panel within Chrome DevTools using Angular and Typescript. Through my efforts, I have successfully implemented a new Panel by utilizing the code snippet provided below: chrome.devtools.panels.create(&ap ...

Creating a custom Angular 4 validator that relies on a service to access a list of valid values

I have a task to create a directive that validates whether an input value is part of a dynamic list of values. The list of values is passed as a parameter to the directive: @Directive({ selector: '[lookup]', providers: [{provide: NG_VALIDATORS, ...

Warning: NgOptimizedImage Optimization_NOTICE

Exploring the latest features of angular 15 to enhance image performance led me to encounter this cautionary message. `The NgOptimizedImage directive (used on an <img> element with `ngSrc="/assets/fascinating.png") has detected that the ori ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

Refreshing the cache in SWR, but the user interface remains unchanged inexplicably - SWR hook in Next.js with TypeScript

I am currently working on a project that resembles Facebook, and I am facing an issue with the like button functionality. Whenever I press the like button, I expect to see the change immediately, but unfortunately, SWR only updates after a delay of 4-8 sec ...

Guide to making a Typescript interface by combining elements from two separate interfaces without utilizing inheritance

Programming Language: Typescript I am looking to combine the properties of two interfaces as the value of an indexable-type within a third interface. Interface 1: export interface Employee { id: string name: string } Interface 2: export interfa ...

A Guide to Retrieving Parameters and Request Body using Express and Typescript

When I use the PUT method, I encounter this issue: const createFaceList = (req: Request<{faceListId : string}>, res: Response, next: NextFunction) => { console.log(req.body.name); console.log("faceListID = " + req.params.faceListId); a ...

Tips on ensuring all fields are mandatory in a form

Currently, I am in the process of working on my Angular2 project. Specifically, I have created a form and my intention is to make all fields required. However, I encountered an issue when attempting to make the Title field mandatory as it is not displaying ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

Troubleshooting: Socket.io integration in Angular is not functioning within a .then() statement

Upon running this code snippet in a component: const videoholder = <HTMLDivElement>( document.querySelector('#videoholder') ); const myPeer = new Peer(this.userid, { host: '/', ...

Angular and KeyCloack - Automatically redirect to specific route if user's role does not have access permissions

I am currently working on implementing a mechanism to redirect unauthorized roles when attempting to access restricted routes using the keycloack-angular library: npm install keycloak-angular keycloak-js Custom Guard Implementation export class AuthGuar ...

Encountered Angular SSR Serve Error: NullInjectorError - StaticInjectorError in AppServerModule with the following reference:

While working on building an application with Angular's SSR and serving it, I encountered a specific error. All services and components have been properly injected. Error: ERROR Error [NullInjectorError]: StaticInjectorError(AppServerModule)[REQUEST] ...

Add the mat-ripple effect to the host element with Angular 5 attribute directive

Is there a way to automatically include the mat-ripple directive on the host element of a custom directive I've made? The goal is to have mat-ripple added seamlessly to any element that uses my custom directive. For instance, when I add <button my ...

Can you explain the concept of System.register in a JavaScript file?

Can you explain the purpose of System.register in a JS file when utilizing directives in Angular 2? ...

Disabling the use of console.log() in a live environment

In an effort to disable console logs for production environments in my angular application, I implemented the code below. While it successfully suppresses logs in Chrome, IE 11 continues to display them. Here is the snippet from main.ts: if (environment. ...

Angular OAuth2 OIDC password reset process

Currently, I am integrating B2C into my Angular (8) application using angular-oauth2-oidc. I have successfully implemented sign-in and sign-out policies, as well as configuring the angular-oauth2-oidc service. However, when utilizing the standard Microsoft ...

Ways to retrieve the most recent value from an Angular 4 subscription

What is the best way to retrieve the most recent value from a subscribe method in Angular 4? this.AbcSrvice.value.subscribe(data => {console.log(data)}) ...