What is the process for managing multiple selections using checkbox code?

I have been following the official tutorial for ag-grid and I've reached a point where I need to manipulate information related to selected checkboxes. However, the documentation lacks detail on how the code actually functions. It might be understandable since it's not their responsibility to provide in-depth explanations. But as someone with limited experience working with Angular technology, I find it challenging to truly grasp the workings of the code!

The html file instructs me to add the following:

<button (click)="getSelectedRows()">Get Selected Rows</button>  

And in app.component.ts, I need to include this:

getSelectedRows() {  
        const selectedNodes = this.agGrid.api.getSelectedNodes();   
        const selectedData = selectedNodes.map(node => node.data);   
        const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');   
        alert('Selected nodes: ${selectedDataStringPresentation}');   
    }  

If there is someone who can explain what exactly the typescript code is doing, that would be greatly appreciated. Thank you!

Answer №1

  • It appears that agGrid is the platform where your simulated data is stored, retrieving an array of information from elsewhere.
  • The array selectedData is generated by converting (without modifying the original array) the selectedNodes array and extracting only the data property from each node.
  • selectedDataStringPresentation performs a similar operation, but this time it compiles formatted strings by combining the make and model properties of each object in selectedData.

You may be overlooking the implementation of ES6 (JavaScript standard) functions used in this context, particularly the map() function.

You can reference the official documentation for the map() function on arrays here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

In essence, the map() function cycles through an array, applying a specified function to each element and returning the results as a new array.

To illustrate with selectedData, you can interpret the process like this:

  • Iterate through each object in selectedNodes, extract the data property, and store in a new array.

This feature proves handy when handling distinct arrays with varied purposes. For instance, if you have a service containing a catalog of objects and receive an array of IDs representing those objects from a backend service, you can employ the map() function to effortlessly convert the array of IDs into an array of corresponding objects from your service.

Answer №2

Oh no! @Alex Beugnet beat me to the punch with an upvote. Nevertheless, I'll still post my response since I was in the middle of composing it.


Before diving into Enable Selection section of the guide, let's check your familiarity with TypeScript. Apologies if this seems basic, but clarity is key for understanding the logic behind your question.

In the "Enable Selection" part of the guide, you're essentially enabling multiple row selection in the grid and getting data from those selected rows upon button click.

To better understand what's happening with the getMultipleRows() function, visualize it using the Debugger in browsers like Chrome Developer Tools (press F12). It's highly recommended for grasping the underlying logic.

const selectedNodes

Let's say we select two rows - Porsche Boxster 72000 and Ford Mondeo 32000. Clicking 'Get Selected Rows' triggers the getSelectedRows() function:

const selectedNodes = this.agGrid.api.getSelectedNodes();

This line assigns the constant variable 'selectedNodes' RowNodes from AgGrid. By utilizing the AgGridNg2 method getSelectedNodes(), you receive an array in the form of:

[RowNode, RowNode] //(one for each selected row)

Each RowNode contains various properties as provided by AgGrid, but focus solely on the 'data' property for now.

const SelectedData

const selectedData = selectedNodes.map(node => node.data);

'selectedData' becomes an array of RowNode.data, extracting the data property from RowNodes into a new array. You can think of it as:

let selectedData = [];

for (let i = 0; i <= selectedNodes.length - 1; i++){
    selectedData[i] = selectedNodes[i].data;
}

The 'selectedData' would appear as:

[
    {
        make: "Porsche",
        model: "Boxster",
        price: 72000,
    },
    {
        make: "Ford",
        model: "Mondeo",
        price: 32000
    }
]

const selectedDataStringPresentation

const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');

This step concatenates Make and Model from selectedData array into a single element with commas. Resulting in "Porsche Boxter, Ford Mondeo".

Lastly,

alert('Selected nodes: ${selectedDataStringPresentation}');

An alert will display the selectedDataStringPresentation array in the browser for viewing.

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 efficient images using Node.js and express using sharp or canvas

Struggling with optimizing image rendering using node, express, and sharp. Successfully implemented an upload method with Jimp for images over 2000px wide and larger than 2mb in file size. While many libraries can achieve this, Jimp was more memory-effici ...

There seems to be an issue with Kurento-rtsp2webrtc functionality on AWS

After following the instructions of the kurento-rtsp2webrtc tutorial to stream RTSP on a website, I was able to successfully run the demo in a local network environment. However, when attempting to run it on AWS EC2 with VPN, everything worked fine. Unfor ...

Angular material table footer calculations

I am currently utilizing Angular Material Table version 8.2.3 to generate multiple tables from a TypeScript definition. The majority of these tables are related to numerical data, requiring me to display totals in the footer section. However, I am facing a ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

What could be causing the concave walls in my ray casting engine when applying fisheye correction?

As I work on creating a ray casting engine using HTML Canvas, I encountered the fisheye effect issue. Most online resources suggest multiplying the ray's length by the cosine of its angle from the player to correct this problem. distance * Math.cos( ...

The Jest snapshot test fails to capture any styling applied to children components

Struggling with creating a snapshot test for a straightforward react-native component. Jest's snapshot lacks necessary styling and content details for the single child of the component. The component is a basic button from native-base with an icon em ...

Having a single quote within a double quote can cause issues with JavaScript code

I am currently developing a Django web app and facing an issue with sending a JSON object to my JavaScript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "te ...

Having trouble finding module: Unable to locate 'fs' - yet another hurdle with NextJS

Trying to access a JSON file located one directory above the NextJS application directory can be tricky. In a standard JavaScript setup, you might use the following code: var fs = require('fs'); var data = JSON.parse(fs.readFileSync(directory_pat ...

What are some effective ways to integrate the WordPress API with ReactJS?

Wordpress recently introduced an API that allows you to make HTTP requests without worrying about routes, as the backend is handled for you. I'm curious, how can I integrate ReactJs with Wordpress API? This has been a frustrating challenge for me be ...

Peer dependency conflict detected: @angular/[email protected]

When attempting to incorporate Android into my Ionic project, I encountered the following error: Error: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/<a href="/cdn-cgi/l/email-protection" ...

After the recent update to rc2, the Angular2 quickstart app has suddenly stopped functioning as expected

After updating my angular2 app, originally based on the tutorial / quickstart app, from rc1 to rc2, everything seemed fine: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="325f5b5c5b5f5346515a72001c021c0302" ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...

pagination functionality incorporated into element ui tables

Issue with Element UI: when a checkbox is selected and the page is changed, the selected rows' checkboxes are removed. I need to retain the selection items while paging so that users can select items from multiple pages without losing the selections f ...

When using Websocket, an error message stating "Invalid frame header" will be triggered if a close message of 130 or more characters is sent

I am utilizing the ws node.js module along with html5's WebSocket. The Websocket connection is established when a user triggers an import action, and it terminates once the import is completed successfully or encounters an error. At times, the error ...

Implementation of chained if-else if statements using dot.js

Exploring the doT.js template engine and wondering about the nested if-else if syntax in dot.js. How can we achieve it in a structure like this: if() ..... else if ..... else if ..... else ..... ...

Can anyone help me understand the meaning of this unfamiliar icon in WebStorm's autocomplete feature

When the autocompletion feature is performing type inference, you will see this icon: https://i.sstatic.net/zOZcC.png ...

The improved approach to implementing guards in Angular

I am currently looking for the most effective way to utilize Angular "guards" to determine if a user is logged in. Currently, I am checking if the token is stored. However, I am wondering if it would be better to create an endpoint in my API that can verif ...

Activate animation upon scrolling to specific element using Material-UI

Currently building out a website using react and Material-UI, I am looking to enhance the user experience with some transitions. At the moment, I have a button set up to display a component, but I want it to show up when I scroll to that specific part of ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows: https://i.stack.imgur.com/YgFjd.png The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds whi ...