Tips for choosing and unchoosing rows in angular 6

I am looking to extract the values from selected rows and store them in an array. However, I also need to remove a row from the result array when it is deselected. The issue with my current code is that every time I click on a row, the fileName values are being added to the result array (selectedRows) as many times as I clicked on the row. Here's a snippet of my code:

HTML:

<ag-grid-angular #grid
      style="width : 603px; height:250px;" class="ag-theme-balham"
      [rowData]="searchResults" [columnDefs]="columnDefs" [rowSelection]="selectionMode"
      [rowMultiSelectWithClick] = true
      (rowClicked)="onRowClicked($event)"
    >
    </ag-grid-angular>

component.ts:

export class ShowFilesComponent implements OnInit {
            searchResults : Array<String>;
            private selectedRows :Array<String>;

            columnDefs  = [
                {headerName:"S No", valueGetter: (args) => this.getIndexValue(),checkboxSelection : true,headerCheckboxSelection: true,
                headerCheckboxSelectionFilteredOnly: true,cellRenderer: 'selectedClient'}, 
                {headerName : 'File Name', field:'fileName', sortable:true},
                {headerName : 'word count', field:'wordCount', sortable:true}
              ]
            constructor(private http: HttpClient,private r : Router, private s : FileListService) {
                this.http.get(this.path).subscribe(
                  (data: any) => {
                    this.searchResults = data;
                    console.log(this.searchResults);
                  },
                  error => console.log(error)
                );

               }
            }
            ngOnInit() {}
             onRowClicked(event){
            this.selectedRows.push(event.node.data.fileName);

                console.log(this.selectedRows);
}
        }

Answer №1

To add an element to an array, you can utilize the Array.prototype.push method as shown below:

onRowClicked(event){
    let temp = 0;
    this.selectedRows.push(event.node.data.fileName);
    console.log(this.selectedRows);
}

For removing an element from the array when deselected, you can make use of the splice method. Most table or grid components have a deselect event that allows you to easily remove elements from the array.

Answer №2

To monitor the selection or de-selection of a row, it is necessary to subscribe to the onRowSelected event.

Here is an example code snippet from the ag-grid-angular community forum that can serve as a foundation for your customization (the data provided below is purely for demonstration purposes).

Angular Code:

var gridOptions = {
  columnDefs: columnDefs,
  rowSelection: 'multiple', // enable multiple row selection with click
  rowMultiSelectWithClick: true,
  rowData: null,
  onRowSelected: onRowSelected // subscribe to row selection event
};

function onRowSelected(event) {
     alert("row " + event.node.data.athlete + " selected = " + event.node.selected); // for debugging only
     if(event.node.selected) {
         this.seletectedRows.push(event.node.data.athlete);
     } else {
       const index = this.seletectedRows.indexOf(event.node.data.athlete);
       if(index != -1) {
          this.seletectedRows.splice(index, 1);
       }
     }
}

Live demo on plunkr

Answer №3

To make changes to the grid selection, you need to set up a selectionChanged handler with the grid component. Within this handler, utilize the getSelectedNodes() method provided by the grid api.

<ag-grid-angular #grid
      [rowData]="searchResults" [columnDefs]="columnDefs" [rowSelection]="selectionMode"
      [rowMultiSelectWithClick]=true
      (selectionChanged)="onSelectionChanged($event)" >
</ag-grid-angular>

The event object will contain a reference to the grid api, giving you access to the selected rows...

onSelectionChanged(event: AgGridEvent) {
  const nodes = event.api.getSelectedNodes();
  // Perform actions with the selected rows....
}

It's worth noting that there is no need to manually store the nodes in an array as ag-grid keeps track of this for you automatically. You can simply leverage Array.map() to extract any desired data from the node objects.

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

Adding a ng-select field when a button is clicked

In my template, I am using ng2-select to allow users to select items. There is a button called "Add" that, when clicked, should display another select field with a list of different item categories. However, the current version of my code does not achieve ...

Styling multiple checkbox items in an Angular Material Autocomplete

Is there a way to adjust the height of autocomplete multiple checkbox items in Angular Material? I'd like it to look like this With a line item height of 18px But instead, it looks like this when using multiple checkboxes With a different checkbox ...

Error: Attempting to access the 'environment' property of a null value is not allowed

I am experiencing an issue with my Ionic 4 app that utilizes @ionic-native/google-maps. The error stack trace I am seeing is as follows: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'environment' of null TypeError: Cannot ...

By pairing delay(0) with refCount(), we can achieve optimal efficiency

The refCount operator is discussed in this article. It explains the necessity of adding delay(0) to prevent unsubscription of observable A: import { Observable } from "rxjs/Observable"; const source = Observable.defer(() => Observable. ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Issue with Angular 2: Route guard failing to work after browser refresh

Defining these routes in app.module.ts: ... { path: 'mypath', component: MyComponent, canActivate: [RouteGuard] }, { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '**', redirectTo: '/ho ...

Having issues with jsonConvert.deserializeObject not functioning in angular2 json2typescript

Greetings, I am new to Angular 2 and working on fetching user data from Google, Facebook, and LinkedIn. I am attempting to deserialize an object into an instance of a class I created named UserLogin, but unfortunately it does not seem to be working. Here ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

Error in vue3 with typescript: unable to assign a ComputeRef<number[]> argument to an iterable<number> in d3.js

This code snippet was originally sourced from an example at https://medium.com/@lambrospd/5-simple-rules-to-data-visualization-with-vue-js-and-d3-js-f6b2bd6a1d40 I attempted to adapt the example to a TypeScript/Vue 3 version, and below is my implementatio ...

Activate the mat-select selectionChange trigger when making changes to the form via patchValue

I have been working with an angular reactive form that includes a mat-select element with a selectionChange event. After updating the form using patchValue, I noticed that the selectionChange event does not trigger. I'm unsure how to proceed and woul ...

Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript? I attempted to implement this solution, but it only affects the first element. ngAfterViewInit () { const matlabel = this.elRef.nativeElement.querySelecto ...

Understanding the Use of Promises and Async/Await in Typescript

Struggling with asynchronous libraries in Typescript, I find myself looking for a way to wait for promises to be resolved without turning every method into an async function. Rather than transforming my entire object model into a chain of Promises and asyn ...

Discovering the root cause of performance issues in a v14 Angular application

I am currently working on a web application built with Angular 14. During my testing with Lighthouse, I have discovered that the performance of the application is satisfactory on desktop but falls short for mobile users. The application consists of three ...

Utilizing a syntax highlighter in combination with tsx React markdown allows for cleaner

I'm currently looking at the React Markdown library on Github and attempting to incorporate SyntaxHighlighter into my markdown code snippets. When I try to implement the example code within a function used for rendering posts, I encounter the error de ...

No routes found for URL segment 'master-system/update-system'

I seem to be missing something crucial while attempting to set up authorization for child routes. Specifically, I am trying to restrict access based on user roles - Admin and notAdmin. I have implemented an authentication check in the login.component.ts fi ...

Integrate AngularJS service with Angular framework

Attempting to utilize the $log service within an angular 2 app, it seems that the following steps are necessary: Set up a module that includes the service you wish to inject. Utilize UpgradeAdapter's upgradeNg1Provider method. Therefore, I proceede ...

Adding dropdowns to divs in Angular applications

Currently, I am attempting to integrate a dropdown feature into a div element. The HTML code for the dropdown is generated dynamically within the code. When clicking on the dropdown button, it appears functional but unfortunately, the dropdown itself does ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Extracting data from an action using NgRx8

Hey everyone, I'm looking for some guidance on how to destructure action type and props in an ngrx effect. I'm struggling with this and could use some help! This is my list of actions: export const addTab = createAction( '[SuperUserTabs ...