Combining 2 dates into a single cell format

I'm struggling to change the date format of two dates displayed in one cell using ag-grid. I have tried creating a new function called dateFormatterr with two parameters, but it doesn't seem to work. Below is a snippet of my code and a screenshot of the ag-grid in question:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'app';
  gridOptions = {
    rowHeight: 70
  }
  columnDefs = [{
      headerName: "Block \n Deal",
      cellRenderer: function(params) {
        return params.data.BLOCKID + '<br/>' + params.data.DEALID
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Class \n Type',
      cellRenderer: function(params) {
        return params.data.DEALCLASS + '<br/>' + params.data.DEALTYPE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Trade \n Start',
      cellRenderer: function(params) {
        return params.data.TRADEDATE + '<br/>' + params.data.STARTDATE
      },
      valueFormatter: this.dateFormatterr('TRADEDATE', 'STARTDATE'),
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Folder \n Cpty',
      cellRenderer: function(params) {
        return params.data.FOLDERSHORTNAME + '<br/>' + params.data.CPTYSHORTNAME
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'ShortName \n Name',
      cellRenderer: function(params) {
        return params.data.INSTRSHORTNAME + '<br/>' + params.data.INSTRNAME
      },
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Quantity \n Settl.Amt',
      cellRenderer: function(params) {
        return params.data.QUANTITY + '<br/>' + params.data.SETTLEAMT
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Rate \n Fees',
      cellRenderer: function(params) {
        return params.data.FLOATINGRATESSHORTNAME + '<br/>' + params.data.RENTSPREADFIXEDRATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Category \n Status',
      cellRenderer: function(params) {
        return params.data.DEALCAT + '<br/>' + params.data.WORKFLOWSTATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'End',
      field: 'ENDDATE',
      valueFormatter: this.dateFormatter,
      width: 140,
      resizable: true,
      filter: true
    },
  ];
  rowData: any;
  constructor(private service: DealsService) {}
  dateFormatter(params) {
    return moment(params.value).format('DD/MM/YYYY');
  }
  dateFormatterr(params1, params2) {
    return moment(params1.value + params2.value).format('DD/MM/YYYY');
  }
  ngOnInit() {
    this.service.getDealsList().subscribe(data => {
      this.rowData = data;
    });
  }
}

Your assistance with this issue is greatly appreciated. Thank you.

Answer №1

To implement a custom cell renderer component for the Trade Start column, follow these steps:

  1. Develop an ag-grid custom cell render component that implements ICellRendererAngularComp interface.
  2. Specify the DateCellRendererComponent as the cellRendererFramework in the column definition of the Trade Start column.
  3. Ensure to register the custom cell render component in your application module.

date-cell-renderer.component.html

<p>{{trDate}} <br />{{strtDate}}</p>

date-cell-renderer.component.ts

    import { Component } from '@angular/core';
    import { ICellRendererAngularComp } from 'ag-grid-angular';
    import * as moment from 'moment';

    @Component({
       selector: 'app-comment-cell-renderer',
       templateUrl: './comment-cell-renderer.component.html',
       styleUrls: ['./comment-cell-renderer.component.scss']
    })
    export class DateCellRendererComponent implements ICellRendererAngularComp {
       params: any;
       trDate: string;
       strtDate: string;

       refresh(params: any): boolean {
            return false;
       }

       agInit(params: any): void {
            this.params = params;
            this.trDate = moment(params.data.TRADEDATE).format('DD/MM/YYYY');
            this.strtDate = moment(params.data.STARTDATE).format('DD/MM/YYYY');
       }

       constructor() { }
   }

app.component.ts

columnDefs = [
    {
      headerName: 'Trade \n Start',
      cellRendererFramework: DateCellRendererComponent,
      width: 150,
      resizable: true,
      filter: true,
    }
];

app.module.ts

import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  imports: [
    AgGridModule.withComponents(
      [ DateCellRendererComponent]
    )
  ]
})

Answer №2

The function dateFormatter should only accept a single parameter instead of two. Here are the steps to follow within the function:

  1. Using regex/pattern or a custom function, split the two date strings into separate strings.
  2. Convert each string into a date format.
  3. Sum the two dates using moment and return the result.

I am unable to provide the code as your screenshot does not display all the necessary date information.

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

Combining attributes of objects in an array

Is the title accurate for my task? I have an array structured like this: { "someValue": 1, "moreValue": 1, "parentArray": [ { "id": "2222", "array": [ { "type": "test", "id": "ID-100" }, { ...

What is the purpose of running "npm install" if the "node_modules" directory already exists?

When "npm install" is run on a project directory containing both a "package.json" file and a "node_modules" directory, what impact does it have? Does it replace the current modules with newer versions? Does it update them, or does it have no effect at all ...

The key to subscribing only once to an element from AsyncSubject in the consumer pattern

When working with rxjs5, I encountered a situation where I needed to subscribe to an AsyncSubject multiple times, but only one subscriber should be able to receive the next() event. Any additional subscribers (if still active) should automatically receive ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

Avoiding Re-renders in an Angular2 Countdown Component

I am facing an issue with my Angular2 master component that includes multiple child components and a standalone countdown component called "clock". The countdown component updates its label every second, causing unnecessary re-rendering of the master compo ...

Hiding the C3 tooltip after engaging with it

I'm currently expanding my knowledge on utilizing C3.js for creating charts, and one aspect I'm focusing on is enhancing the tooltip functionality. Typically, C3 tooltips only appear when you hover over data points as demonstrated in this example ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

Facing issues with Angular 13 migration: Schema validation encountered errors stating that the data path "/error" needs to be a string

Currently in the process of migrating from Angular 8 to 13 and encountering an issue. I have been following the guidelines outlined on https://update.angular.io/, however, every time I attempt to build certain custom libraries from my application root fold ...

How can I determine if a URL in react js includes a specific string?

I am working on a project where I need to check if a given URL contains the string youtube using react hooks in React JS. This is what my current code looks like: useEffect(() => { let srcLink = "www.google.com/https://img.youtube.com/vi/h9-qcy3HQn ...

The transitions on my jQuery Mobile page are not functioning correctly

I am currently working on a custom MVC structure using Handlebars and jQuery Mobile. To manually manage routing, I have disabled two jQM parameters: $.mobile.linkBindingEnabled = false; $.mobile.hashListeningEnabled = false; These lines disable link bind ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

Creating a dynamic slider using jQuery

Here is the code snippet I have been working on: var current_slide = 1, animation_time = 1000, pause = 3000, slide_container = $('.slide_container'), interval, height = slide_container.height(), slides ...

Determine the Button's State by Monitoring Changes in the TextBox Text

I have been tasked with developing a web application for my company. The main components of the application are a button and a textbox. My goal is to allow users to input a value into the textbox, which will then be processed when they click on the button ...

The command npm install -g . fails to copy the package

The guidelines from npm's developer documentation suggest ensuring that your package can be installed globally before publishing by executing the command npm install -g .. I am currently working on developing an ES6 Command Line Interface (CLI) packag ...

Is it possible to initiate a request action in both the constructor and ngOnInit method?

I am facing a situation where I need to trigger a request action from both the constructor and ngOnInit functions in order to load data. However, I have noticed that on the second call, one of the dispatch actions is not being invoked and the data remains ...

Choosing Angular.json setups while executing a Docker multi-stage construction

I am currently in the process of developing an Angular6 application with a Docker multistage build. The default angular.json file generated by angular.cli includes a build section containing various configurations. To choose a specific configuration, I can ...

Omit assets in final version

During development (ng serve), I have specific assets like images and styles that I use. These assets are not needed in the production build as they are provided by a CDN. My requirements are: When using ng serve, I want to serve files from the folder . ...