What is the proper way to implement a function with a value formatter when the column definition is already predefined within quotation marks in AG-Grid?

When working with JSON data that specifies columnDefs and uses valueFormatters as a function, it is essential to correctly format the valueFormatter. For instance, if the JSON data reads valueFormatter: "dateFormatter" instead of valueFormatter: dateFormatter, how can one access the function?

The JSON is currently written as: (valueFormatter: "dateFormatter"), but in order to utilize valueFormater as a function, it should be written as: (valueFormatter: dateFormatter).

Answer №1

An improved approach to this task is to utilize Custom Column Types.

Simply include the type property in a column within your JSON:

{field:"athlete", type:"athleteType"}

Then connect the [columnTypes] Grid property:

<ag-grid-angular
    [columnDefs]="columnDefs"
    [columnTypes]="columnTypes"
    /* other grid options ... */>
</ag-grid-angular>

Within the columnTypes, you can now define your valueFormatter function:

// define a column type (multiple definitions possible)
this.columnTypes = {
    athleteType: { valueFormatter: params => 'athlete' },
};

Answer №2

If you decide to use a String for this process, the grid may not render correctly at first because it will attempt to format with the String.

Therefore, shortly after setting it up, you will need to update the columnDefs.

You will need to locate the function, update the columnDef to have the valueFormatter point to the function, and then use setColumnDefs and refreshRows to rebuild the DOM with the function assigned.

For example:

// obtain the current column definitions
var columnDefs = gridOptions.api.getColumnDefs();

// iterate through each one
columnDefs.forEach(colDef =>{
    // if it has a valueFormatter
    if(colDef.valueFormatter){
      // and it is a string
      if(typeof colDef.valueFormatter == "string"){
        // if the function is found
        if(window[colDef.valueFormatter] 
           && typeof window[colDef.valueFormatter]=="function"){
              // assign the function as the valueFormatter
              colDef.valueFormatter = window[colDef.valueFormatter];
        }
      }
    }
  });

// reconfigure the grid with the updated definitions
gridOptions.api.setColumnDefs(columnDefs);

// trigger a redraw to apply the function
gridOptions.api.redrawRows(); 

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

Tips for implementing Conditional validation in form models in anugular2

I need to determine whether the required validator for Address should be applied based on the value of this.type being 2. Below is the code snippet I am using for form validation: buildForm() { this.orgForm = this.fb.group({ Name: [this.addUpd ...

Organizing validators within reactive forms in Angular

When creating a form in Angular, I have multiple fields that need validation. Below is the code I am using to create the form: requestForm = this.formBuilder.group({ requestorName: ['', [Validators.required]], requestorEmail: ['&apo ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...

The error code TS2474 (TS) indicates that in 'const' enum declarations, the member initializer must be a constant expression

Error code: export const enum JSDocTagName { Description = "desc", Identifier = "id", Definition = "meaning", } Implementing Angular 6 in conjunction with the .NET framework. ...

When the query result is received in Angular TypeScript, translate epoch time into a time string

Here is the dilemma I am currently facing: I have an Angular script that requests data from a backend service and receives query results to display to the user. One of the fields in the query response is a time stamp, which is currently in epoch time forma ...

Angular 10 - Compilation errors caused by the element's location

When running 'ng serve' or 'ng build' in Angular 10, I encountered a build error that stated: ERROR in projects/project-navigator/src/app/modals/building-permissions.component.html:89:61 - error NG8002: Can't bind to 'ngClass& ...

How to submit a form in Angular2 without reloading the page

I have a straightforward form to transmit data to my component without refreshing the page. I've tried to override the submit function by using "return false," but it doesn't work as expected, and the page still refreshes. Here is the HTML: ...

The Typescript Module augmentation seems to be malfunctioning as it is throwing an error stating that the property 'main' is not found on the type 'PaletteColorOptions'

Recently, I've been working with Material-UI and incorporating a color system across the palette. While everything seems to be running smoothly during runtime, I'm facing a compilation issue. Could someone assist me in resolving the following err ...

manage dynamic form data in React using Ant Design components

My attempts to work with dynamic forms using React and Ant Design have been challenging. Despite my efforts to find solutions online, I have had no luck. Here is a CodePen link where I have recreated the issue I am facing: https://codepen.io/sethen/pen/Rwr ...

Error: Unable to access the property 'fn' of an undefined object in electron version 2 using Angular 6

I am currently utilizing Angular 6.0.3 and electronjs 2.0.2 with the package.json configuration shown below: { "name": "test", "version": "1.0.0", "license": "MIT", "main": "electron-main.js", "author": { "name": "Moh ...

Creating autorest client based on various OpenAPI versions

I'm currently exploring options for creating a Typescript client from our .NET API. After researching various tools, I decided to go with Autorest, as it is Node-based and fits my skillset. While I am aware of Swashbuckle, my knowledge leans more towa ...

Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage. https://i.sstatic.net/GbphJ.png Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code sn ...

Encountering subscription API issues from MongoDB following a route modification

I developed a service to retrieve data from the MongoDB API. Initially, everything was functioning properly. However, upon switching to another route and then returning, the data became undefined. Only after refreshing the browser did it revert back to its ...

Angular seat map for booking a flight

I'm stuck and in need of assistance. I am trying to change the color of a seat (add or remove a class) in Angular, but I can't figure out how to do it. Here is my current solution using JS: https://codepen.io/mateuszcieslik/pen/mdpLqgw. I have a ...

Accessing the menu

There are two main headings in my menu: Administration and Market https://i.sstatic.net/JbePq.png When I click on the Administration heading, submenus for Portfolio and Corporate Action are displayed https://i.sstatic.net/oyabv.png The issue I am facin ...

Submitting Angular data to PHP back-end is a common practice

I am attempting to send data from Angular to PHP. Angular POST Request var body = { "action":"getvouchernumber","vouchertype": vtype, "vmonth": vmonth, "vyear":vyear }; return this.http.post(this.BaseURI+& ...

Passing an object from an Angular application to a backend server in Node.js using the

I have a YAML file with the following structure: Layouts: - Name: Default Layout LayoutId : 1 ConfiguredSegments: LiveA : Height : 100 Id : LiveA Ref1A : ...

Tips for displaying HTML content dynamically in React using TypeScript after setting a stateVariable

To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows: const formService = new FormService(); const [appointmentDate, setAppointmentDate] = us ...

Validating Emoji Inputs in Angular

Is there a way to validate input for Emoji and display an error message if invalid? The form field in question is: 'name': new FormControl('', [Validators.required]), ...

Is there a way to prevent an undefined legend from being automatically created in an ng 2 chart during the loading process?

While working with the ng-2 chart, I noticed that an undefined legend is automatically generated in the stacked bar chart with a color that I did not specify. I am using a specific set of colors defined in an array. Is there a way to remove only the undefi ...