Retrieve ag grid from TypeScript file

I am currently utilizing ag-grid-angular in my Angular application to showcase data. I have a button that is located outside the ag grid, and when it is clicked, I need to retrieve all row data from the grid. I am aware that there is an API available for accomplishing this task. Essentially, what I am trying to do is access the ag grid from my TypeScript file. Below is the code snippet for reference.

Code in the TypeScript file:

this.columns = [
  {},
  {headerName: 'First Name', field: 'firstName'},
  {headerName: 'Last Name', field: 'lastName'}
];

this.rows = [
    {"", "first name1", "last name1"},
    {"", "first name2", "last name2"}
];

Code in the HTML component:

<ag-grid-angular id="myGrid" #agGrid style="width: 100%" class="ag-theme-balham" [rowData]="rows" [columnDefs]="columns">
</ag-grid-angular>

I would greatly appreciate any guidance on how to achieve this functionality.

Thank you

Answer №1

If you are using AgGrid, there are various APIs available for accessing and configuring data within the grid.

One key API to be aware of is GridApi, which can be accessed once the Ag grid has been initialized through the gridReady event.

Take a look at the code snippet below for more insights:

import { Component } from '@angular/core';
import { GridApi, GridReadyEvent } from 'ag-grid-community';

@Component({
  selector: 'app-root',
  template: `
    <ag-grid-angular
      style="width: 100%; height: 500px;"
      class="ag-theme-balham"
      [rowData]="rows"
      [columnDefs]="columns"
      (gridReady)="onGridReady($event)"
    ></ag-grid-angular>
    <br />
    <button (click)="getData()">Get Data</button>
  `
})
export class AppComponent {
  columns = [
    { headerName: 'First Name', field: 'firstName' },
    { headerName: 'Last Name', field: 'lastName' }
  ];

  rows = [
    { firstName: 'first name1', lastName: 'last name1' },
    { firstName: 'first name2', lastName: 'last name2' }
  ];

  gridApi: GridApi;

  onGridReady(params: GridReadyEvent) {
    console.log(params);
    this.gridApi = params.api;
  }

  getData() {
    if (!this.gridApi) {
      return;
    }
    const rowCount = this.gridApi.getDisplayedRowCount();
    for (let i = 0; i < rowCount; i++) {
      const rowNode = this.gridApi.getDisplayedRowAtIndex(i);
      console.log(`row ${i + 1} -> `, rowNode.data);
      // Perform your logic
    }
  }
}

For more information, refer to the official documentation of Ag-Grid Angular. Happy coding!

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

What is the best way to merge multiple nested angular flattening operators together?

I am facing a challenge in utilizing the outcomes of Observables from various functions. Some of these functions must be executed sequentially, while others can run independently. Additionally, I need to pass the result of the initial function to some nest ...

Steps to perform a task that relies on two observables

I'm currently working on a function that requires two responses from two separate asynchronous functions, both returning observables. 1. Func1 returns an observable 2. Func2 returns an observable These functions are independent and can be executed sep ...

What sets 'babel-plugin-module-resolver' apart from 'tsconfig-paths'?

After coming across a SSR demo (React+typescript+Next.js) that utilizes two plugins, I found myself wondering why exactly it needs both of them. In my opinion, these two plugins seem to serve the same purpose. Can anyone provide insight as to why this is? ...

Sorting Angular data using database queries

I'm currently setting up a blog for my website. Everything is running smoothly with the database, but I've run into an issue with the order of my posts - they are displayed in the opposite order that I want. The oldest post is showing at the top, ...

Manipulating objects from an HTTP Observable while iterating through an Array of objects

I am currently working on processing each element of an array by making a separate HTTP call for each element. I need to track the status of each call and update the UI once all calls are completed. The code snippet below demonstrates my current approach: ...

Angular's Async Pipe displaying outdated data

I am encountering an issue with my Angular async pipe setup. Here is the code snippet: <ng-container *ngIf="showProjects && (projects | async) as projectList; else loading"> In my projects.page.ts file, I have the following funct ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

Utilizing shared components across a Next.js application within a monorepo

Utilizing a monorepo to share types, DTOs, and other isomorphic app components from backend services (Nest.js) within the same mono repo has presented some challenges for me. In my setup, both the next.js app and nest.js app (which itself is a nest.js mono ...

Trouble Loading TypeScript Class in Cast Situation

I've encountered an issue with my TypeScript model while using it in a cast. The model does not load properly when the application is running, preventing me from accessing any functions within it. Model export class DataIDElement extends HTMLElement ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

After updating to Angular 15, the web component fails to function properly on outdated versions of Chrome

Ever since upgrading Angular to version 15, my angular web component stopped functioning properly on Chrome 53. The issue seems to be related to the compilerOptions setting the target to ES2022. Upon checking the console, I am seeing the error message: Un ...

Creating conditional keys using the Zod library based on the value of another key

Incorporating the TMDB API into my project, I am making an effort to enhance type safety by reinforcing some of the TypeScript concepts I am learning. To achieve this, I am utilizing Zod to define the structure of the data returned by the API. Upon invest ...

Encountering issues with upgrading Vue.js 2.5.2 with TypeScript

I am currently in the process of updating vue js to version 2.5.2 along with typescript 2.5.3. Below is my index.ts file: import Vue from 'vue' var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' ...

Determining the Type<> of a component based on a string in Angular 2

Can you retrieve the type of a component (Type<T>) based on a string value? For example: let typeStr: string = 'MyComponent'; let type: any = getTypeFromName(typeStr); // actual type ...

Exclude a select few rows in MatSort, rather than excluding entire columns

When the user clicks on the Date column for sorting, it is required to exclude empty rows from the sorting. Empty rows are present due to the application of ngIf on those particular rows. The requirement states that rows with empty column values should eit ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Change icons in Ionic 5 when selecting a tab

How can I change my tab icons to outline when not selected and filled when selected? The Ionic 5 Tabs documentation mentions a getSelected() method, but lacks examples on its usage. I plan to utilize the ionTabsDidChange event to detect tab clicks, then ...

Tips on programmatically filtering angular lists

Is there a way to programmatically filter an Angular list? I'm currently working on a project where I need to filter subcategories by clicking on categories. For example, when clicking on "Drinks," I want to display items like Coke, Fanta, Pepsi... ...

I keep encountering the ExpressionChangedAfterItHasBeenCheckedError error in Angular, even though I'm calling it before the view is checked. What could

This is a piece of code that I have been working on home-component.ts export class HomeComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked { loading = false; constructor() { } ngOn ...

Guide on loading HTML templates into tab content within an Angular application

I am currently working on a project using Angular 8. After reading an informative article, I gained an understanding of concepts like ContentChildern, QueryList, and successfully built a sample tabs component. Here is the link to the article for reference ...