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

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

Retrieving data from Firebase query and displaying as an array of results

Currently utilizing the @react-native-firebase wrapper for interaction with Firebase's Firestore. Within my function, some querying to a specific collection is performed, with the expected result being an Array object containing each located document. ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Turning a JSON formatted string into parameters for a function

Looking to convert a string of JavaScript objects into function arguments. The string format is as follows: "{ "item1": "foo 1", "item2": "bar 1" }, { "item1": "foo 1", "item2": "bar 2" }" While I can use JSON.parse to turn it into an array, the challeng ...

Save all dynamically received data from a form in PHP as an array

I have developed a PHP form that dynamically adds new text variables in this manner: <form action="" enctype=”multipart/form-data” method="post" action="<?php echo $_SERVER['REQUEST_URI'];?>"> <div id="div"> va ...

What is the best method for transmitting all parameters via a URL?

$(document).ready(function () { $("#submitButton").click(function () { var name = $("#name").val(); var age = $("#age").val(); var gender = $('input:radio[name=gender]:checked').val(); v ...

The console is being flooded with API logging messages multiple times

My goal is to develop a search page for Pathfinder. I have crafted the following code in an attempt to retrieve data from the API. During the process of testing the fetch requests, I have noticed that when I console.log the fetched data, it appears multipl ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Arrange pictures into an array and showcase them

I'm encountering some difficulties with organizing my images in an array and displaying them in a canvas element. Javascript code snippet canvas = document.getElementById('slideshow'); canvasContent = canvas.getContext('2d'); va ...

Is using the new Date function as a key prop in React a good

In my React code, I have been using new Date().getTime() as key props for some Input components. This may not be the best practice as keys should ideally be stable. However, I am curious to know why this approach is causing issues and why using Math.random ...

Substituting text in a document by utilizing two separate arrays: one holding the original text to be found and another storing the corresponding text for

I am facing a challenge with replacing specific text strings in a file. I have two arrays - one containing the strings that need to be located and replaced, and the other containing the replacement strings. fs.readFile("./fileName.L5X", "utf8", function( ...

Issues persist with the Angular UI Tree Module: the removed callback is not functioning as

I am currently utilizing a module that can be found at the following URL: https://github.com/angular-ui-tree/angular-ui-tree Unfortunately, I am facing an issue with getting the removed callback to work properly. The accept callback seems to be functionin ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

How can one retrieve information from within a vue.js function?

As a newcomer to VueJS, I am seeking help on updating data upon click. Below is my code snippet: <div id="elementApp"> <div class="element">{{ message }}</div> <button class="button" v-on:click="nextElement()">Next data</but ...

All fields in the form are showing the same error message during validation

This is the HTML code: The form below consists of two fields, firstname and lastname. Validation Form <form action="" method="post"> Firstname : <input type="text" placeholder="first name" class="fname" name="fname" /> <span class= ...

Tips for initializing a jstree with no content?

When I click a button, I send a key to the controller and retrieve my lists using JSON. The array inside my lists serves as my children in my jstree. $("#btnSearch").on("click", function () { alert("I'm also here"); $.ajax({ ...

When using Vue, it is important to ensure that dynamic slot names error templates are solely utilized for accurately mapping the state to

I am encountering an issue with Vuejs(2.6.11) Dynamic Slot Names: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed. Why is this error occurri ...

What could be causing the format to be incorrect?

docker run -it -v "%cd%":/e2e -w /e2e cypress/included:6.2.1 --browser chrome When attempting to execute this command within Visual Studio Code, an error is encountered: docker: invalid reference format. See 'docker run --help' Vario ...

Utilizing $templateCache with ui-router and minifying in AngularJS 1.x

Posting this as a question-answer post. How can one effectively utilize the $templateCache in the templateProvider of a route within ui-router when attempting to refactor the code? Injection is ineffective, and Angular cannot inject by reference. For ins ...