Is there a way to modify the color of a specific row by its index position?

My table has cell editing functionality using primeng, and the data is fetched from an API which results in varying row quantities and orders. I want to dynamically change the row color to red if the word size is incorrect or green if the size is correct.

I believe I need to capture the index of the edited row and then apply the color change accordingly.

<p-table [value]="valProd" responsiveLayout="scroll" (onEditInit)="onEditInit($event)" (onEditCancel)="onCancelInit($event)"> 
  <ng-template pTemplate="header"> 
    <tr> 
     <th>Name</th> 
     <th>Value</th> 
     <th>Size</th> 
    </tr> 
  </ng-template> 
   <ng-template pTemplate="body" let-valProd let-rowData> 
      <tr> 
      <td>
        <p-cellEditor>
         <ng-template pTemplate="output">
           {{ rowData.Name}}
         </ng-template>
       </p-cellEditor>
     </td>
         <td [pEditableColumn]="rowData.Value" pEditableColumnField="rowData.Value"> 
          <p-cellEditor [ngStyle]="{'background': colorTry}"> 
           <ng-template pTemplate="input"> 
            <input pInputText 
              type="text" 
              [(ngModel)]="rowData.Value" 
              name="value"
              (change)="checkWriteValue(rowData.Value, rowData.Size, rowData.HasFixedLength, rowData.Name)"
                                (keydown.enter)="checkWriteValue(rowData.Value, rowData.Size, rowData.HasFixedLength, rowData.name)"
> 
          </ng-template> 
          <ng-template pTemplate="output" id="pruebainput"> 
            {{rowData.Value}}
          </ng-template> 
        </p-cellEditor> 
      </td> 

      <td>
        <p-cellEditor>
         <ng-template pTemplate="output">
           {{ rowData.Size}}
         </ng-template>
       </p-cellEditor>
     </td>
   </tr> 
 </ng-template> 
</p-table>   

I attempted to use ngstyle for this purpose but all rows were affected. I need a way to work with each row independently.

The goal here is to verify the size of the word when the cells are edited by pressing enter or losing focus. If the size is correct, the row background should turn green; if it's incorrect, it should turn red. Multiple rows can have the same color.

Answer №1

If you want to achieve this using only CSS, you can give it a try. Since PrimeNG has built-in validation (as shown in the screenshot), you just need to handle it.

Your CSS could look something like this (please note that I have not verified it):

tr {
  background: green;
}

tr:has(.ng-dirty.ng-invalid) {
  background: red;
}

https://i.sstatic.net/zpvyH.png

Answer №2

There exist two possible solutions to tackle this particular issue.

The initial method involves highlighting rows in color only if their default values satisfy the condition. On the flip side, the alternative approach refrains from coloring rows unless they possess 'ng-dirty', but specifically when it contains 'ng-dirty'.

Initial Solution

To combat this, utilize ngClass to designate the background color of the row.

Incorporate ngClass in your HTML as demonstrated below:

<tr
    [ngClass]="{'not-valid-length': rowData.Value.length > 10, 'valid-length' : rowData.Value.length < 10}"
  >
    ...
  </tr>

Employ 'not-valid-length' for your CSS class and specify 'rowData.Value.length' as the condition for adding the class to the table row.

Add these lines to your CSS/SCSS file:

:host ::ng-deep .not-valid-length {
     background-color: rgba(185, 24, 24, 0.15) !important;
    }

    :host ::ng-deep .valid-length {
     background-color: rgba(102, 185, 24, 0.15) !important;
    }

Alternative Solution

To alter the row's color once the input cell undergoes modification, modify the body template by incorporating 'let-i="rowIndex"' into the template and manipulating the row within said template.

let-i="rowIndex"
<ng-template pTemplate="body" let-valProd let-rowData let-i="rowIndex">... 
</ng-template>

Subsequently, append 'rowIndex' to the table row:

<tr [id]="'tableRow' + i">...</tr>

The inclusion of the 'i' parameter with the rowIndex ensures each row possesses a unique ID for identifying the edited input cell's row. The row index proves vital in the checkWriteValue method for setting the row's color, necessitating an update to said method within the HTML code.

<p-cellEditor [ngStyle]="{'background': colorTry}">
        <ng-template pTemplate="input">
          <input
            id="input"
            pInputText
            type="text"
            [(ngModel)]="rowData.Value"
            name="value"
            (change)="checkWriteValue($event, i)"
            (keydown.enter)="checkWriteValue($event, i)"
          />
        </ng-template>
        <ng-template pTemplate="output" id="pruebainput">
          {{rowData.Value}}
        </ng-template>
 </p-cellEditor>

After executing these steps, proceed to edit the component.ts file.

checkWriteValue(event: any, index: number) {
let input: HTMLElement = document.getElementById('input');
let tableRow: HTMLElement = document.getElementById('tableRow' + index);
if (input.classList.value.includes('ng-dirty')) {
  if (event.target.value.length > 10) {
    tableRow.classList?.remove('valid-length');
    tableRow.classList.add('not-valid-length');
  } else {
    tableRow.classList?.remove('not-valid-length');
    tableRow.classList.add('valid-length');
  }
}

}

The checkWriteValue method accepts 'event' and 'index' as parameters, affixing CSS classes to the table row. It comprises two 'if' statements: one scrutinizing the presence of 'ng-dirty' in the input's class list, and the other gauging the length of the new value input to ascertain the suitable CSS class. This results in appending 'not-valid-length' or 'valid-length' classes to the row's class list. (edit note: Due to potential bugs arising from prior classes not being deleted, additional methods like classList.remove('valid-length') were implemented. Commenting out those lines may unveil erratic behavior.)

Please exercise caution when employing :host and ::ng-deep selectors.

I have rigorously tested my solution which has yielded positive outcomes. Feel free to test it yourself here.

If you require further assistance, do not hesitate to reach out. I am here to lend a helping hand.

Answer №3

One clever solution for incorporating colors in a React project is to create an array containing at least 50 different color values. Then, you can dynamically generate rows based on your data by looping through and applying inline styles with background colors according to the index.

const colors = ['#a2a2a2','#e2e2e2','#515151',...];

data.map((item,i)=>(
<row style={{backgroundColor:colors[i]}}></row>
));

Alternatively, if you're working with plain Javascript, you can utilize CSS :nth-child selector to assign background colors to individual rows.

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

Is it possible to increment an integer value in jQuery after obtaining the sum result?

Actually, I'm trying to extract the integer value from my input field. For example, if I enter the value 4+5, I want to display the result as 9 in a separate div. However, instead of getting the expected result, I am receiving [object Object]. I&apo ...

Extract the data from an HTML form and transfer the values into variables within a node.js function

Issue Description: I am facing a challenge in my project where I need to take three numbers as input from the user through an HTML form. Upon submission, I want these values to be passed to a node.js file and stored in variables. Here is the HTML code sni ...

Is it feasible to utilize JavaScript to access and modify local files?

Every day at work, I find myself going through the same repetitive process: Start by opening a specific Dreamweaver file. Hunt down all <p> tags and swap them out with <h1> tags. Locate every </p> tag and replace it with </h1>. Se ...

Error encountered while trying to display the react-bootstrap table

I am having trouble rendering sample data using react-bootstrap tables. Every time I try, I encounter the error: TypeError: Cannot read property 'filter' of undefined I've searched on various platforms and visited multiple links, but I ca ...

StatusChanges retrieves the previous status prior to the execution of AsyncValidators

When checking for errors using statusChanges, I display the resulting array of errors in the html template. To validate input asynchronously, I utilize an asynchronous validator. The sequence of events is as follows: Upon entering text or losing focus in t ...

Achieving compatibility between angular-bootstrap modal and angular-1.3

Wondering if anyone has managed to successfully use angular-bootstrap modals with angular-1.3.x? I've had no issues with my modals on angular-1.2.x, but as soon as I upgraded to angular-1.3.11, the modals stopped showing up. When I click the button ...

Exploring JSONPath in Cypress

I am currently working on extracting a JSON path for the specific HTML content with the language code DE Below is an example of the JSON data: { "name": "Name", "text": "", "html": "HTML content" ...

Tips for utilizing an Array in React Lifecycle:

Working with Mongo/Meteor 1.3/React has presented an interesting challenge for me. In a basic scenario, I have utilized a wrapper React component to fetch data from a Mongo collection and create an Array. However, when passing this Array to the Child compo ...

Personalize the 'Standard', 'Fresh', and 'Modify' aspx widget devoid of Share Point or Infopath integration

As I work on developing a Sharepoint 2010 page to meet my team's needs, I am faced with restrictions on using Sharepoint Designer and InfoPath. This means I am unable to customize the default form for adding, editing, or viewing items on my individual ...

Top strategy for incorporating sprite background images, optimized for search engine optimization

When it comes to using sprite images for icons that are linked without any associated text, the best method in terms of SEO is up for debate. Here are a few different examples of how the markup could be implemented: Option 1: Individual Images <a hre ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

Angular: Initial value displayed in component due to cookie not being available during first execution of APP_INITIALIZER, updates to new value upon re-render

Within my Angular v18 application with SSR functionality enabled, I am encountering an issue when attempting to access a cookie within the APP_INITIALIZER function. I have integrated ngx-cookie-service and followed their guidelines for SSR setup. The app. ...

What is the process for testing an NGRX effect that relies on a store selector?

Currently, I am facing an issue with testing Jest for an NGRX effect that utilizes a store selector. The main problem lies in the inability to mock the return value of the selector due to the function 'select' being imported from '@ngrx/stor ...

Is regex the reason why the website isn't showing up properly on mobile devices?

I encountered an issue on my Vue.js website hosted on Firebase where a blank white page was displayed on mobile devices. After some investigation, I traced the problem back to two objects declared in the data function of one of my components: re: { you ...

The typescript-eslint-parser does not officially support this version of TypeScript

I recently acquired an outdated AngularJs application that still relies on the legacy tools: bower and grunt. Upon executing grunt serve --reload, I encounter the following warning message: WARNING: You are currently running a version of TypeScript which ...

Troubleshooting Rxjs issues related to a chain of operators

Encountering an issue with the switchMap operator: @Injectable() export class AvailableStoreTypesLoadedEffect { constructor(private actions$: Actions, private service: AvailableService) { } @Effect() AvailableStoreTypesLoadedEffect$ = this.a ...

Difficulty with timing in React.js when rendering content from an Express.js API

I am facing a timing issue while working with React.js. My component checks the validity of the user's token and type. If the user is an admin, it should display certain content; otherwise, it should show "you don't have permission". However, I ...

Tips to detect a specific animation completion on an element?

How can I ensure that a specific animation ends when multiple animations are triggered on an element? My scenario involves an overlay song list that appears when a list icon is clicked. The challenge lies in closing the menu smoothly. I have implemented a ...

What is the reason behind the constraints of min/max width and height values preventing the element from fully filling its parent div?

HTML Code: <div class="content"> <div class="card"> </div> </div> CSS Code: .content { min-height: 350px; min-width: 320px; max-width: 350px; padding: 15px; } .card { width: 100%; height: 100%; ...

React Checkbox Fails to Update Status

Whenever a checkbox is toggled to true, I need to update an array. However, with my current code, clicking on a checkbox logs that it's false even after updating the state. It seems like setState might take some time, similar to an API call, which doe ...