Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The goal is to be able to select rows based on which checkboxes are checked within the ag-grid.

Below is the code for the child component:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.js"></script>
<template>
<input type="checkbox" :id="inputId" :name=name @click ="clickHandler($event)" />
</template>
<script>
  import Vue from 'vue';
  export default Vue.extend({
    name: 'CheckBoxRenderer',

    data: function() {
      return {
        id: '',
        name: '',
        inputId: '',
        rx1List: [],
        rx2List: [],
      };
    },
    beforeMount() {
      this.id = this.params.data.id;
      this.name = 'rx' + this.id;
      this.inputId = this.params.column.colId + '_' + this.id; // if colId(headerName) ="rx1", and id is 2, inputId = rx1_2
    },
    methods: {
      clickHandler(e) {
        //console.log(e.target.checked, this.params.column.colId); //  to get Header name use colId property
        var group = document.querySelectorAll(`input[name="${this.name}"]`);
        // console.log(group.length);

        if (e.target.checked) {
          for (var i = 0; i < group.length; i++) {
            //console.log(group[i].checked);
            group[i].checked = false;
          }

          e.target.checked = true;
          if (this.params.column.colId === 'rx1') {
            this.rx1List.push(this.id);
          }
          console.log(this.rx1List);
        } else {
          e.target.checked = false;
        }

      }
    }
  });
</script>
<style scoped></style>

Here is the parent component's ag grid column definition:

 {
                field: "rx1",
                headerName: "Rx1",
                cellRendererFramework: "checkBoxRenderer",
                valueSetter: function (param) {
                    var id = "rx1_" + param.data.id;
                    alert("if check box checked?: ", document.querySelector(id).checked);
                    param.data.rx2 = document.querySelector(id).checked;
                    console.log("Rx2: ", param.data.rx2);
                    return param.data.rx2;
                },
                flex: 1,
                maxWidth: 80,
                cellStyle: { textAlign: "center"},
                
            },

Answer №1

To streamline the process, define the click handler in the parent component and then pass it down to the child as a prop. By doing this, the child component will only need to call the prop while the parent component keeps track of the checked state(s) and renders the grid accordingly. Below is a simple and contrived example:

Vue.config.productionTip = false;

const Child = {
  name: 'Child',
  props: ['onCheck'],
  methods: {
    handleCheck(e) {
      console.log(`${e.target.checked ? 'Checked' : 'Unchecked'}, let's call our onCheck prop`);
      this.onCheck(e);
    }
  },
  template: `<div><input type="checkbox" id="checkbox1" @change="handleCheck($event)" /></div>`,
}

const Parent = {
  name: 'Parent',
  data() {
    return {
      state: false,
    };
  },
  methods: {
    handleCheck(e) {
      console.log("Got a click event from child!");
      this.state = e.target.checked;
    }
  },
  components: { Child },
  props: [],
  template: '<div><Child :onCheck="handleCheck" /><div>state: {{ state }}</div></div>',
};

const App = new Vue({
  el: '#root',
  components: { Parent },
  template: '<Parent />',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root"></div>

On a side note, consider using @change instead of @click for checkboxes.

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

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

In search of assistance with creating a function that can transform an asynchronous function into a time-limited version

Let's discuss the challenge requirements: Given a function called fn that operates asynchronously and a time limit t in milliseconds, the goal is to create a new version of this function with a time constraint. This new function should behave accordi ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

Total aggregate for a variety of Sliders (Bootstrap 4 & jQuery)

I am currently working on a web page that involves implementing 3 sliders. The total of all three sliders should always be limited to 100%. This project utilizes the Bootstrap 4 framework and jQuery 3.6.2 Here are my current challenges: The combined valu ...

Struggling with React integration of AdminLTE3 sidebar treeview?

I have a requirement to create a React sidebar with a category 'Staff' that, when clicked, reveals three subordinate categories. Below is the code snippet: import React, { Component } from "react"; export default class Sidebar extends Componen ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

Encountering an issue when trying to submit a post request: "Received an API resolution without a response for /api/comments, which could lead to delayed requests."

Hey, I recently started diving into Next.js and I'm facing an issue with making a POST request to the API. In my project structure, I have a comments folder nested inside the api folder. Within the comments folder, I've written the following cod ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Issue with socket.io: Server unable to emit event to client upon connection

I'm struggling with my basic socket.io setup as I can't seem to get my server to send a message once the connection is established. Upon establishing a connection to my server, I want it to automatically send a message back to the client. Here&a ...

Creating Unique Identifiers in ExpressJS

I am currently utilizing mongoose to display admin and user information on a dashboard, but I am encountering difficulty rendering the id of a user. Below is the code I am using: function ensureAuthenticated(req, res, next){ if(req.isAuthenticated()){ ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Focusing on the active element in Typescript

I am working on a section marked with the class 'concert-landing-synopsis' and I need to add a class to a different element when this section comes into focus during scrolling. Despite exploring various solutions, the focused variable always seem ...

When I try to pass a variable as a prop to another .js file, it mysteriously transforms into an undefined value

Upon successful login, my app file sets the isAuthenticated variable to true and redirects to the /admin page. The Firebase API call is functioning as expected, allowing access only with a valid username and password. The issue arises when I try to hide t ...

Configuring JSON in PHP and JavaScript

Although I have already asked this question before, I am experiencing some issues in my code. I know that utilizing JSON is necessary and after researching multiple sources, I grasp the concept but somehow am unable to implement it correctly. Here is my co ...

Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller. Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when ...

Navigate through the document object model and identify every pair of input boxes sequentially to build a JavaScript object

Incorporating a varied number of input boxes into a view based on selections made in a combo box. For instance, selecting '1' from the combo box results in two input boxes being added to the view. Choosing '2' adds four input boxes. Ea ...

I am encountering a JQuery syntax error while using Bootstrap 3 button-dropdown links

I'm trying to replicate the example found here in order to create a similar markup: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ...

Displaying the table header only once within a VueJS component

Currently, I am working on a search functionality built in VueJS which displays the search results in a separate component. My goal is to showcase this data in a table format with appropriate headings. However, I am facing an issue where the table headin ...

Exploring the concept of JSON within node.js

As I work on creating an Alexa skill using node.js, I'm facing a challenge in defining a JSON element. Specifically, I need to gather all the titles from a news API and include them as variables in my code. Although I have successfully logged the titl ...