Steps for showing an item in ag grid in Angular

Cannot see the data being displayed. Here is the code snippet: Click here to view the code

list.component.ts

setAgGrid() {
    this.data.map((data: any) => {
      const date = new Date(data.date);
      const year = ('' + date.getFullYear()).slice(-2);
      const assetColIndex = data.assetCode + '_' + date.getMonth() + '_' + year;

      if (this.columns.indexOf(assetColIndex) === -1) {
        this.columns.push(assetColIndex);
      }
    });

    const dataByMonthYr = this.data.reduce((dataByMonthYear: any, datum: any) => {
        // Code continues here...
    }, []);

    this.columnDefs.sort((a: any, b: any) => {
      if (a.code < b.code) { return -1; }
      return 0;
    });


    console.log(this.columnDefs, dataByMonthYr);
    this.rowData.next(dataByMonthYr);
  }

How can I display the objects in ag grid?

I want the output to look like this: https://i.sstatic.net/dJpQZ.png

When trying to add

this.gridOptions.gridApi.setRowData(object)
, the gridApi or setRowData function is not recognized. Expected output: https://i.sstatic.net/AYrFi.png Thank you in advance.

Answer №1

To properly display the object in row data, you must set it within the rowData object like this: [rowData]="rowData" within your TypeScript file, assign the object to rowData.

Alternatively, you can utilize the setRowData method: this.gridApi.setRowData(object);

If you need to customize how a cell is displayed, consider using a cellRenderer. You can find more information on this at https://www.ag-grid.com/javascript-grid-cell-rendering-components/

Answer №2

Reason for GridApi being undefined:

The reason why your GridApi is showing as undefined is because it has not been properly initialized.

To fix this, you need to include the gridReady event in your template like so:

(gridReady)="onGridReady($event)"

In your component, make sure to add the following code:

onGridReady(event){
 this.gridApi = event.api;
 this.setAgGrid();
}

Solution for data not displaying:

https://i.sstatic.net/w8wxO.png

After reviewing the image provided: It seems that your columnDefs and rowData are not properly synced with what you want to display.

The issue lies in the fact that your columnDefs only contains one object with a 'code' field value.

You should add additional fields to match the columns you wish to display.

Ensure that the keys in your 'rowData' object names match the field names in your columnDefs.

You can remove the redundant call to setAgGrid from the ngOnInit method.

Note: Changing the hide property from false to true in your columnDefs will make your code column visible. There's no need to use BehaviorSubject, simply assign the array directly to your rowData.

Answer №3

After examining the code, I have identified numerous issues ranging from syntax errors to logical errors. Utilizing my basic comprehension of the code, I have attempted to address these problems.

To ensure that the setAgGrid() method is called after the ag-Grid has been initialized, utilize the gridReady event of ag-Grid as shown below:

(gridReady)="onGridReady($event)"

In your component file, replace the OnInit method with a new function:

onGridReady(event){
 this.gridApi = event.api;
 this.setAgGrid();
}

Additionally, modify the lines inside the setAgGrid() method like so (I included a new line of code and updated another line).

this.gridApi.setColumnDefs(this.columnDefs)
this.gridApi.setRowData(dataByMonthYr);

Substitute the if condition in the code with the following one, as the column definitions were not added to the columnDefs array due to an issue with the else condition within the two if cases.

if (colHeaderIndex !== -1) {
        const colIndex = this.columnDefs[colHeaderIndex]
          .children.findIndex((data: any) => data.field === assetColIndex);
        if (colIndex === -1) {
          this.columnDefs[colHeaderIndex].children.push(
            {
              'headerName': datum.assetCode,
              'field': assetColIndex,
              'aggFunc': this.customAggFunction
            }
          );
        }
      } else {
        this.columnDefs.push({
          headerName: monthYear,
          code: date.getMonth() + '_' + year,
          children: [
            // { headerName: "Style/Machine", field:   },
            { headerName: datum.assetCode, field: assetColIndex, width: 100, aggFunc: this.customAggFunction },
          ]
        });
      }

I encountered a similar outcome as described in your question. Additionally, I have developed a stackblitz demo which can be accessed here - https://stackblitz.com/edit/ag-grid-angular-hello-world-wcss8k

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

Having trouble getting the styles property to work in the component metadata in Angular 2?

Exploring Angular 2 and working on a demo app where I'm trying to apply the styles property within the component metadata to customize all labels in contact.component.html. I attempted to implement styles: ['label { font-weight: bold;color:red } ...

How to Retrieve the Following Element in a Table Using Javascript

https://jsfiddle.net/en6jh7pa/1/ I am encountering an issue with accessing the next element, as it is returning null. When I pass "this" as the onclick parameter, I expect to be able to grab the next element using this keyword. However, it seems to be re ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

JMeter recording displays a script alert error notification

After recording the JMeter script on blazemeter, it initially worked fine on the website. However, upon running the jmx file, I encountered an error message: "alert("Something went wrong. Please try again");window.history.back();" I&a ...

Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form. Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'. The issue arise ...

Unable to retrieve a method from the model class in Angular 4

I attempted to utilize a method from the model class, but encountered an error: ERROR TypeError: act.sayHi is not a function Below is my code snippet: Model Class myModelClass.ts export interface IMymodel { name: string; addres ...

Progress bar for uploading files

Similar Question: Upload Progress Bar in PHP Looking for suggestions on a simple and effective method to implement a file upload progress bar. Interested in a solution that involves both javascript and php. Any recommendations? ...

The issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

How to Identify Clicks within Nested Divs in Angular 4+ and Differentiate them from External Divs

I've come across numerous Angular 2 pages that iterate through a hierarchy of nativeElements. However, these methods seem to be ineffective in Angular 4, 5, and beyond. I'm looking to incorporate a directive into a "workspace" DIV. This workspace ...

ReactAwesome Slider Autoplay Feature

I've been tinkering with a React Awesome Slider that you can find here: https://github.com/rcaferati/react-awesome-slider I've managed to implement it successfully, but I'm struggling to make it autoplay every 10 seconds. I assume I need to ...

Acquiring data from a server using React and Express: Fixing the error "TypeError: Cannot read property '' of undefined"

My challenge lies in parsing a JSON response received from my server within the client-side code. When I make a simple request to my mongoDB server: GET http://localhost:4000/food/ I receive the following response, which consists of an array of objects. ...

What could be causing the React state not to update properly?

Having an issue with my Alice-Carousel in react. I'm fetching items from an API and updating the array for the carousel, but the value of items keeps coming back as undefined. Using CryptoState context to avoid prop drilling. import React from 'r ...

When capturing photos using h5 on iOS devices, the browser may experience a flash back issue

I have been searching Baidu and Google for a while now, but I still haven't found a solution. Here is the specific issue: When using h5 to take photos on iOS systems, the browser flashes back. HTML Code <img src="xxx" onclick="sta ...

Nuxt.js ERROR: Unable to find reference to 'window' object

Currently working with Nuxt.js and encountering an issue while configuring vuex-persist. Seeking assistance from someone familiar with this problem. store/index.js store/LangModule.js ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

Sending handlebars variable to the client-side JavaScript file

I am currently working on an application using node.js along with express and handlebars, and I'm trying to find a way to transfer handlebars data from the server to client-side JavaScript files. Here is an example: //server.js var person = { na ...

Create a React Native layout with a set width and the ability to stretch to fill

Is there a way to achieve this layout in react-native? I am looking to have a component with a fixed width on the right side, while another component on the left side takes up the remaining space. https://i.sstatic.net/3c6q6.png ...

Presenting Ajax Sample Outcomes while the Form is Loading

With my Ajax form displaying water data from the US Geological Survey and a Google chart, everything is working smoothly. However, I want new users to see some sample results right away instead of an empty box upon loading the form. I am unsure of how to a ...

A guide on exporting table data to PDF and enabling printing features in Angular 7

Can anyone provide guidance on how to export my dynamic table data into Excel, PDF, and for printing using the appropriate Angular Material components and npm plugins? I have successfully exported the data as an Excel file, but am struggling with exporti ...

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...