Unable to properly display date formatting in AG-Grid using the Angular date pipe

Currently, I am utilizing ag-grid in conjunction with Angular 8. Within my table, there is a column where my intention is to exhibit dates in a concise format. In order to achieve this, I opted to utilize the Angular date pipe. However, it appears that the implementation is encountering issues. The code snippet and error message are provided below:

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {

  @ViewChild('agGrid', {static: true}) agGrid: AgGridAngular;

  rowData: Bidon[] = [];
  columnDefs = [
    {headerName: 'PostId', field: 'postId', sortable: true, filter: true, checkboxSelection: true},
    {headerName: 'Id', field: 'id', sortable: true, filter: true},
    {headerName: 'Name', field: 'name', sortable: true, filter: true},
    {headerName: 'Email', field: 'email', sortable: true, filter: true},
    {headerName: 'Body', field: 'body', sortable: true, filter: true},
    {headerName: 'Date Bidon 1', field: 'dateBindon1', sortable: true, filter: true, valueFormatter: this.datePipeFormatter},
    {headerName: 'Date bidon 2', field: 'dateBidon2', sortable: true, filter: true},
    {headerName: 'Price', field: 'price', sortable: true, filter: true, valueFormatter: this.currencyFormatter}
  ];

  constructor(private bidonService: BidonService, private datePipe: DatePipe) {
  }

  ngOnInit() {
    this.rowData = this.bidonService.bidons;
    console.log(this.datePipe.transform(new Date(), 'short'));
  }

  getSelectedRows() {
    const selectedNodes = this.agGrid.api.getSelectedNodes();
    const selectedData = selectedNodes.map(node => node.data);
    const selectedDataStringPresentation = selectedData.map(node => 'Name: ' + node.name + ' Email: ' + node.email).join(', ');

    console.log(`Selected nodes: ${selectedDataStringPresentation}`);
  }

  currencyFormatter(params) {

    console.log(params);
    return params.value + '$';
  }

  datePipeFormatter(params) {

    return this.datePipe.transform(params.value, 'short');
  }

}

enter image description here

Answer №1

When ag-grid calls your valueFormatter function, the this context is lost, so you need to bind it.

Using bind:

columnDefs = [
    {headerName: 'PostId', field: 'postId', sortable: true, filter: true, checkboxSelection: true},
    {headerName: 'Id', field: 'id', sortable: true, filter: true},
    {headerName: 'Name', field: 'name', sortable: true, filter: true},
    {headerName: 'Email', field: 'email', sortable: true, filter: true},
    {headerName: 'Body', field: 'body', sortable: true, filter: true},
    {headerName: 'Date Bidon 1', field: 'dateBindon1', sortable: true, filter: true, valueFormatter: this.datePipeFormatter.bind(this)},
    {headerName: 'Date bidon 2', field: 'dateBidon2', sortable: true, filter: true},
    {headerName: 'Price', field: 'price', sortable: true, filter: true, valueFormatter: this.currencyFormatter.bind(this)}
  ];

Alternatively, using arrow functions:

columnDefs = [
    {headerName: 'PostId', field: 'postId', sortable: true, filter: true, checkboxSelection: true},
    {headerName: 'Id', field: 'id', sortable: true, filter: true},
    {headerName: 'Name', field: 'name', sortable: true, filter: true},
    {headerName: 'Email', field: 'email', sortable: true, filter: true},
    {headerName: 'Body', field: 'body', sortable: true, filter: true},
    {headerName: 'Date Bidon 1', field: 'dateBindon1', sortable: true, filter: true, valueFormatter: p => this.currencyFormatter(p)},
    {headerName: 'Date bidon 2', field: 'dateBidon2', sortable: true, filter: true},
    {headerName: 'Price', field: 'price', sortable: true, filter: true, valueFormatter: p => this.currencyFormatter(p)}
  ];

Answer №2

Your code is experiencing a problem with the valueFormatter function you have set for the Date Bidon 1 column in the columnDefs array. The issue arises because you are using this.datePipeFormatter as the value formatter, but the context of 'this' inside the function refers to the function itself, not the component instance, leading to the datePipe service being unavailable.

To resolve this issue, you can utilize an arrow function for the datePipeFormatter function, which will maintain the correct context of the component instance. Here's how you can adjust the code:

{headerName: 'Date Bidon 1', field: 'dateBindon1', sortable: true, filter: true, valueFormatter: (params) => this.datePipeFormatter(params)},

By making this change, the problem with the date pipe not functioning properly should be resolved. Additionally, ensure that you import the DatePipe in your component:

import { Component, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import { Bidon } from '../bidon';
import { BidonService } from '../bidon.service';
import { DatePipe } from '@angular/common';
...

Lastly, confirm that DatePipe is included in the providers array of your module:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [DatePipe], // <-- add DatePipe here
  bootstrap: [AppComponent]
})
export class AppModule { }

After implementing these changes, the date should display correctly in the short format. If any issues persist, feel free to leave a comment and I will assist in resolving them.

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

I encountered a TypeScript error in React Native when attempting to use "className" with TypeScript

Although I've been using React for a while, React Native is new to me. I recently started using tailwind with import { View, Text } from "react-native"; import React from "react"; export default function Navigation() { return ...

Unidentified object type detected - Material UI

This snippet of code was taken directly from the React Material UI website <Select id="selectedSubusecases" multiple value={stepsState.campaignOverviewStep.selectedSubUsecases} ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Creating an Ionic v4 alert box that redirects users to different pages

I am facing an issue with my ion-alert component where I have set up a message with two options, "To Myself" and "To Someone", that should act like buttons and route to different pages in the application. However, using (click) events or [routerLink] on th ...

Utilizing Angular for Webcam Integration

After trying out this code snippet: <video autoplay playsinline style="width: 100vw; height: 100vh;"></video> <script> navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } }) .then(stream =&g ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

Embracing the power of Typescript with Node and Express?

While trying out the TypeScript Node Starter project from Microsoft, I found myself intrigued. Is it really possible to use TypeScript instead of Node on the server? There are a number of server-side tasks where TypeScript excels: - Building a web API ser ...

Can TypeScript provide a method for verifying infinite levels of nested arrays within a type?

Check out this example The concept behind this is having a type that can either be a single object or an array of objects. type SingleOrArray<T> = T | T[]; The structure in question looks like this: const area: ItemArea = [ { name: 'test1& ...

The dynamic change in the maximum value of the Ngb rating is not being accurately displayed in the length of the

The dynamic change in the maximum value of ngb rating is not being reflected in the length of the stars. Although two-way binding occurs with [max]="", the length of the stars remains unchanged. <ngb-rating [(rate)]="currentRate" [ma ...

Parsing the header parameter in a GET request from Angular within the Spring backend

Recently, I delved into Rest services in Spring and learned from a tutorial that sending parameters to the backend can be done securely through the following method: getCompanyDetails(username:string): Observable<CompanyObject>{ const headers = ...

Efficiently transforming a nested object array into a single dynamic array

// I have a collection of various objects _id: "5e5d00337c5e6a0444d00304" orderID: 10355 orderDate: "2020-03-02" user: _id: "5e2e9699a648c53154f41025" name: "xyz1" email: "<a href="/cdn-cgi/l/email-protection" class="_ ...

typescript Can you explain the significance of square brackets in an interface?

I came across this code snippet in vue at the following GitHub link declare const RefSymbol: unique symbol export declare const RawSymbol: unique symbol export interface Ref<T = any> { value: T [RefSymbol]: true } Can someone explain what Re ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

What are the steps for designing personalized syncfusion grid-columns while still preserving the built-in search functionality of syncfusion?

Looking to transform the data coming from the backend, specifically mapping a user's status which is represented as a number to its corresponding string value. Considered using typescript for this mapping task, but it interferes with syncfusion' ...

Methods for defining a variable in React with Typescript without encountering the "Index signature is missing in type" issue

I am facing an issue while trying to declare a variable 'reports' and assigning it to an array of arrays containing string and number types. The problem arises when I try to assign it, resulting in errors. ... // Retrieving data from an API let ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

Using TypeScript to create a generic type that wraps around HTMLElements

I attempted to execute this action, however the assignment to this.element is not working and I am unsure why. class Elem<T> { public element : T; constructor(typeElement:string){ this.element = document.createElement(typeElement); ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Replace the css variables provided by the Angular library with custom ones

Having an angular library with a defined set of css variables for colors applied to components, which are globally set like this: :root { -color-1: #000000; -color-2: #ffffff; ... } In my application utilizing this library, I need to override ...