What is the best way to update the background color of a row in an AG Grid table when it is clicked

I'm struggling to dynamically change the background color of a row in an ag-grid table when it is clicked. I have attempted using getRowStyle and getRowClass, but those methods only work when the table is initially loaded. I then tried utilizing onrowClicked, but that approach has not been successful.

onRowClicked : row => {
        if (row.data.hasNewData) {
          return { background: '#ff9998 !important'};
        } else if (row.data.hasWrongData === 'Yes') {
          return { background: '#f5ff8b !important' };
        } else if (row.data.hasNoData) {
          return { background: '#acff93 !important' };
        }
      }

I am aiming for the row's background color to update upon clicking based on various data parameters.

Answer №1

It is recommended to utilize the getRowStyle function and manually activate it by using refreshCells() upon clicking the row through the onRowClicked event.

Furthermore, within the getRowStyle callback, ensure to check the node.isSelected() property to determine if the row/node is selected or not.

gridOptions.onRowClicked = function(params) {
  gridOptions.api.refreshCells({
    rowNodes: [params.node],
    force: true // bypasses change detection -> always refreshes the row
  })
}

gridOptions.getRowStyle = function(params) {
  if (params.node.isSelected()) {
    if (row.data.hasNewData) {
      return { background: '#ff9998 !important'};
    } else if (row.data.hasWrongData === 'Yes') {
      return { background: '#f5ff8b !important' };
    } else if (row.data.hasNoData) {
      return { background: '#acff93 !important' };
    }
  }
}

Answer №2

To achieve this, utilize ngFor* and bind a click event with each row:

HTML:

<table>
 <thead>
   <th># Policy ID</th>
   <th>Policy name</th>
 </thead>
 <tbody>
    <tr *ngFor="let policy of policies; let i = index " (click)="changeBackGroud(i)" >
     <div [ngClass]="{'myBackgroud' : row[i].selected}">
      <td>{{policy.id}}</td>
      <td>{{policy.name}}</td>
     </div>
    </tr>
 </tbody>
</table>

TS: Create an array with the same number of items as you are iterating through, assign indices, and add a property "selected = false" initially.

row = policies;

// i represents the index of the selected item
changeBackGroud(i)
{
  row.forEach(function(element) {
      element.selected = false;
        });
  row[i].selected=true;
}

CSS:

.myBackgroud
{
  background:aqua; 
}

You can adjust the CSS styles as needed;

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

Angular: Where does the problem lie - with the application or the deployment?

Currently, I am in the process of creating my own personal website using Angular(v4+). I understand that Angular may seem like a complex framework for a simple website, but I am using it because I am eager to improve my skills with it. During development, ...

Clicking on the <Link to=URL> in a React application built with Typescript and Redux triggers the disappearance of the component

Issue Background The application was created using npx create-react-app rrts --typescript, which sets up React, Redux, and Typescript. Problem Visualization (Content is the component with sentences) View Problem Image Here Problem Description Clicking o ...

Once the submit button is clicked in Angular Dev Extreme, validation processes are triggered once more

Currently experiencing an issue on a page with textboxes and validations. After entering values into the textboxes and clicking submit, the values successfully pass to the database, but the validations continue to appear again upon submitting. This problem ...

Guarding Routes and Navigating Dynamically in Angular

My application features a dynamic navigation bar that changes based on the user's access level within different areas of the product. Utilizing Angulars Route Guards ensures that users can only access routes they have permission for, which has been wo ...

How do I pass a value from my Angular2 directive into the template?

My current setup includes a template named "starrating.component.html" <ng-container *ngFor="let star of arrayStarts"> <span class="glyphicon star" aria-hidden="true" [class.glyphicon-star-empty]="activeStar>=star? false : true" ...

ag-Grid - Apply Row-Level Formatter instead of Column-Level Formatter

I am utilizing ag-Grid to exhibit a financial report structured as follows | Info | Value | |-----------------------|---------------| | Sales | $ 10M | | (-) Production Costs | $ 1M | | (-) Produc ...

Is it possible to use ng-bootstrap with vertical tabs?

I'm experimenting with displaying ng-Bootstrap tabs vertically, but the provided example doesn't quite fit my needs. I'm envisioning a layout similar to what I've sketched in the diagram. Do you think it's achievable? Any suggestio ...

Angular allows for the dynamic updating of og meta tags

Sharing dynamic content on WhatsApp has been made possible through an API. By utilizing the angular Meta class in my component.ts file, I am able to dynamically update the default meta tag property in index.html with the latest content. ...

Avoid generating `.d.ts` definition files during the onstorybook build process in a Vite React library project

I am currently developing a component library using react and typescript. I have integrated Vite into my workflow, and every time I build Storybook, the dts plugin is triggered. This has two undesired effects: It generates numerous unnecessary folders an ...

Unable to resolve host name for registry.npmjs.org on port 80

Hello everyone! I'm currently working on getting my angular library published on npm, but I seem to be running into an issue. When I try to log in, I encounter the following error: npm ERR! code EAI_AGAIN npm ERR! errno EAI_AGAIN npm ERR! request to h ...

Angular: Retrieve the parameter value from the parent route

Having URLs structured like this: www.yoursite.com/accounts/:accountid/info www.yoursite.com/accounts/:accountid/users and so on. An integer value labeled as accountid is embedded within the URL. Despite using the ActivatedRoute parameters, I am unable ...

Tips on showing validation error message through a tooltip when hovering over the error icon in Ionic

Currently, I have implemented bootstrap validation within my Ionic application and it is functioning correctly. The error icon appears within the textbox along with the error message below the textbox. However, I am interested in changing this setup so t ...

Using Express and Node.js, fetch an image from one localhost and transfer it to another localhost

I am currently developing a NodeJs and Angular app The server is running on http://localhost:9000 While the app itself runs on http://localhost:4200 One of my endpoints looks like this http://localhost:9000/users, which I use to fetch all user data The ...

The variable 'selectedvalue' is being accessed before it has been initialized

I'm currently working on sharing the date between components using BehaviorSubject, but I'm encountering an error in the process. public data = new BehaviorSubject<any>(this.selectedValue); public sharedData = this.data.asObservable(); sele ...

Switch things up in the mat-tree angular

Is there a way to change the orientation of a mat-tree-node to "RTL" and adjust the padding to be on the right side? <mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggl ...

Is Error k originating from Angular or Electron?

While utilizing Angular 10 in my Electron application, I encountered some errors after building a release version of the app. These errors are visible in the Chrome Inspector, but it's unclear whether they stem from Electron or Angular, and the messag ...

How can I send form data along with images from Angular to Node.js via an http post request?

When designing this template, I am requesting product information and an image to be stored. <input type="hidden" formControlName="_id"> <input type="file" formControlName="ProductImage" #ProductImage> <mat-form-field> <input for ...

TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...

Ways to show a div when a dropdown option is selected

Currently, I am in the process of designing a form that includes a dropdown menu. Once the user selects a particular option from the list, such as: Software developer a new section will be displayed, showing two additional options: App Developer ...

What is the workaround for using DomSanitizer in a unit test when the component does not automatically inject it?

I have a basic component that does not utilize the DomSanitizer. Let's call it export class ExampleComponent { @Input() public safeHtml: SafeHtml | undefined; } How can I incorporate the DomSanitizer in a unit test? I have attempted to prov ...