What is the best way to combine cells within a single column?

Exploring the code snippet utilizing ag-grid with Vue 3.

<script setup lang="ts">
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
import { AgGridVue } from "ag-grid-vue3";
import { ref } from "vue";

const columnDefs = ref([
    {
        field: "person",
    },
    {
        field: "car",
    },
]);
    
const rowData = ref([
    {
        person: "person-1",
        car: "car-1",
    },
    {
        person: "person-1",
        car: "car-2",
    },
    {
        person: "person-1",
        car: "car-3",
    },
    {
        person: "person-2",
        car: "car-4",
    },
    {
        person: "person-3",
        car: "car-5",
    },
    {
        person: "person-3",
        car: "car-6",
    },
]);
</script>

<template>
    <ag-grid-vue
        style="width: 500px; height: 500px"
        class="ag-theme-alpine"
        :columnDefs="columnDefs"
        :rowData="rowData"
    >
    </ag-grid-vue>
</template>

The above configuration will yield the desired output.

https://i.stack.imgur.com/ioUdd.png

In the presented table, it is possible to group based on the person, but a query arises regarding merging cells in a single column.

https://i.stack.imgur.com/meNOK.png

It appears that implementing row-spanning solely for a single column definition poses challenges as instructing ag-grid to combine multiple cells of a single column within the rowSpan function seems unfeasible. Any suggestions or approaches?

Answer №1

After dedicating several hours to this task, I was able to devise a solution.

Below are the steps I took :

  • In order to implement the functionality of rowSpan, it was necessary to modify the rowData array so that each person's name appears only once. This prevents the rowSpan from considering multiple occurrences of the same person when calculating the row span. Here is how I adjusted the rowData array :

        const uniq = {};
        const rowData = [{
          person: "person-1",
          car: "car-1",
        }, {
          person: "person-1",
          car: "car-2",
        }, {
          person: "person-1",
          car: "car-3",
        }, {
          person: "person-2",
          car: "car-4",
        }, {
          person: "person-3",
          car: "car-5",
        }, {
          person: "person-3",
          car: "car-6",
    }];
    
    rowData.forEach(obj => {
        !uniq[obj.person] ? uniq[obj.person] = true : delete obj.person;
    });
    
    console.log(rowData);

  • Next, I created a function called rowSpan which calculates the number of occurrences of a specific person in the data set.

    function rowSpan(params) {
      const person = params.data.person;
      const gridData = getData(); // The getData() function retrieves the original rowData array.
      return gridData.filter((e) => e.person === person).length;
    }
    
  • Finally, for styling the columns affected by rowSpan, I applied the following CSS styles (sourced from here)

    .show-cell {
      background: white;
      border-left: 1px solid lightgrey !important;
      border-right: 1px solid lightgrey !important;
      border-bottom: 1px solid lightgrey !important;
    }
    

    This is how the columnDefs for the person object are configured :

    {
      field: "person",
      rowSpan: rowSpan,
      cellClassRules: { 'show-cell': 'value !== undefined' }
    }
    

View the Live Demo : Row Spanning Demo

Answer №2

Have you considered if row-spanning could be a viable solution here? Maybe it's worth giving it a shot!

function calculateRowSpan(params) {
  const person = params.data.person;
  return rowData.value.filter((e) => e.person === person).length;
}

const gridColumns = ref([
  {
    field: "person",
    rowSpan: calculateRowSpan,
  },
  {
    field: "car",
  },
]);

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

Angular2: Utilizing filter and search functionalities for an unordered list

Is there a way to implement filtering for an unordered list in Angular using an input field? This specific component creates an unordered list upon page load by fetching data from a JSON file and using the *ngFor directive along with a service. Below is t ...

Guide to sending a binary body in a POST request using Meteor.js

I've been struggling with a challenging issue in Meteor.js that I'm hoping to resolve. My goal is to make API calls to a face detection open API service by sending an image and receiving a JSON object in return. However, I have hit a roadblock as ...

Encountered an error: Unable to access the 'event' property as it is undefined in Laravel 5.3

I'm a beginner with Laravel. Here's my script code that I'm using to retrieve a location in my input field: <script type="text/javascript> google.maps.event.addDomListener(window, 'load', function () { ...

Error: The property 'case sensitive routing' cannot be accessed because it is undefined

Task at hand: Running ExpressJS port using Node.js, nodemon, and lib. Operating System: Windows 10 Home x64 Node.JS Version: Lts The Challenge: Getting the ExpressJS port to run successfully. Current Issue: Encountering an internal file error, potentiall ...

What are the best practices for dynamically handling variables in JavaScript?

I am looking to dynamically work with variables and store their references in a collection. My first question is: How can I save a variable reference (not its value) in a collection? For example: var apple = "A delicious fruit"; var banana = "A yellow f ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

Requiring addresses for Google Maps in order to display directions

To display the directions between two addresses based on the chosen transportation mode, I need to pass the addresses to the code in page 2. After the user selects two cities from a Dropdown box on page 1, they will be sent to the code to show their locati ...

Shut down the active tab

For some reason, using window.close(); in my JavaScript script is not closing the currently opened tab as expected. I'm looking for a way to automatically close a manually opened tab using a JavaScript function. Any ideas on what might be going wrong? ...

Whenever I try to utilize the "ng-list" in JavaScript, I encounter issues accessing the variable model

HTML <input type="text" ng-list ng-model="OtherHobby" />{{OtherHobby}} <br /> {{AllHobbys}} Javascript $scope.OtherHobby = []; $scope.AllHobbys = $scope.OtherHobby; I ran a test on this piece of code. The variable "OtherHobby" w ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...

Angular and RxJS work together to repeat actions even when an HTTP request is only partially successful

I am currently attempting to achieve the following: Initiate a stop request using a stored ID in the URL. Send a request with a new ID in the URL and save this new ID. If the response code is 200, proceed as normal. If it is 204, repeat steps 1 and 2 with ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...

Retrieving a MAC address from a device using a web script or HTTP protocol

Is it feasible, with access to all end user devices, to request the device's MAC address using web scripting in Apache/IIS/Nginx? Would PHP, Perl, or ASP be able to accomplish this task? The client devices run on iOS, so the method described here wil ...

achieve precise outcomes using mapping techniques

I am currently learning react.js and encountering an issue with obtaining specific results on the map. Below is the code I am working with: render(){ const friends = [ {id:1, name: 'Dave',age:50}, {id:2,name: 'Kellie',age:42}, {id:3, ...

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

Extract the ID from the array, save it, and then delete it from the local storage

I am currently developing a mobile application using Angular, JavaScript, Ionic, and Cordova. Within one of my functions, I make use of an array called existingEntries, which is stored as a variable. categories: Array [276] [0...99] 0: Object id ...

Rating of displaying an undefined value (NaN)

I'm having issues with creating a currency conversion calculator, as the result is showing as NaN. Can anyone offer assistance? I've tried multiple solutions but have been unable to resolve it. Check out the following JavaScript code snippet: c ...

Tips for incorporating JavaScript code into back4app.com using Objective-C:1. Start by accessing the

Currently, I am trying to retrieve "ServerDate" from back4app.com using PFCloud. Unfortunately, I have encountered the following issue: Invalid function: "getServerDate" (Code: 141, Version: 1.13.0) When I attempted to use the code below: [PFCloud ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...