Angular - Modify the Background Color of a Table Row Upon Button Click

I am struggling to change the background color of only the selected row after clicking a button. Currently, my code changes the color of all rows. Here is a similar piece of code I have been working with:

HTML

<tr *ngFor="let data of (datas$ | async) | filter:authService.filter | paginate: config | orderBy: key : reverse" [ngClass]="{'data-selected':isSelected}">
    <td>{{data.id}}</td>
    <td>{{data.text}}</td>
    <td>
       <a class="mr-3" (click)="delete(data.id)"><i class="fa fa-remove"></i>
            Remove
       </a>
    </td>
</tr>

TS

delete(postId) {
    this.isSelected=true;
    const ans = confirm('TEXT TEXT '+dataid);
    if (ans) {
      this.dataService.deleteData(postId).subscribe((data) => {
        if(data) {
          this.showSuccessDelete();
        } else {
          this.showError();
        }
        this.isSelected=false;
        this.loadDatas();
      });
    }
  }

CSS

.data-selected{
  background-color: #e9eaea;
}

Any help would be greatly appreciated. Thank you!

Answer №1

You can create a selectedRow attribute in your component class and assign it the value of data.id.

selectedRow: number;

delete(postId, numeroDeposito) {
  this.selectedRow = postId;
  const ans = confirm('TEXT TEXT ' + dataid);
  if (ans) {
    this.dataService.deleteData(postId).subscribe((data) => {
      if (data) {
        this.showSuccessDelete();
      } else {
        this.showError();
      }
      this.isSelected = false;
      this.loadDatas();
    });
  }

}

Then, in the tr tag, use

[ngClass]="{'data-selected': selectedRow === data.id}"
.

Answer №2

If preferred, you can try implementing the following method:

View Live Demo

[class.active]="item.isActive"

and Trigger click event.

(click)="item.isActive = true";

Answer №3

Instead of creating a separate isSelected variable, consider adding it as a property within the data object like this:

{
    id: 1,
    name: 'AA',
    isSelected: false
}

Then, when the delete function is called with data.id as a parameter, you can toggle it accordingly.

deleteMe(id: string) {
    this.data.map(x => x.isSelected = false);
    this.data.find(x => x.id === id).isSelected = true;
}

Update your HTML to reflect these changes:

<tr *ngFor="let item of data" [ngClass]="{selected: item.isSelected}">
    <td>{{item.id}}</td>
    <td>{{item.name}}</td>
    <td><button (click)="deleteMe(item.id)">delete me</button></td>
</tr>

For a working example, check out this demo.

Answer №4

To achieve the desired outcome, you can implement conditional styling.

<div [className]="( checkSelectedRow(i) ? 'example-class' : 'other-class'"></div>

Here is an example of how to do it in Typescript:

checkSelectedRow(rowNumber) : boolean {  
    for(int j=0; j<rows.length; j++){
       if(j==i){
         rows[i]["selected"]=true; return true;
       }; 
    } 
    return false;
}

Answer №5

To tackle this issue, one approach is to create an array consisting of selected rows like so:

  selectedItemList = []

Subsequently, when the remove button is clicked, add the item's ID to the list:

  selectItem(id) { 
    this.selectedItemList.push(id)
  }

Finally, utilize the ngClass directive in the template to apply a certain class if the item's ID is present in the list:

<tr *ngFor="let data of dataList" [ngClass]="{'selected-data':selectedItemList.includes(data.id)}">
   ....
</tr>

Check out the demo 🚀🚀

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

What is the correct way to align my checkboxes with their corresponding labels?

I have been working with HTML to make some adjustments to a website. I recently got feedback to change the label of my checkbox, however, it is now overlapping with another checkbox. How can I resolve this issue? ...

Is there a way to attach a CSS class to a BoundField in order to locate it using jQuery?

I need to assign a specific class name to certain BoundFields within the GridView control. This way, after the GridView has been populated with data and displayed, I would like to have something similar to the following: <td class="Tag1">Some data c ...

Launch the flutter application's web browser and seamlessly navigate back to the app

Currently, I am in the process of developing a mobile application with Flutter, alongside a web version using Angular and Node.js for the backend. I have found myself in need of a unique workflow that involves redirecting users to the web application duri ...

What is the best way to format my JSON data as a table on the screen?

I need to display my data in a table format at the bottom of the screen, as shown in the screenshot below. Here is an example of the top part code: This code snippet is also used for movies. <View> <Text key={item.symbol}>{item.symbol}<Te ...

When a user logs out, Angular assigns a null value to the User object

Currently, I am in the process of creating a basic user authentication application using Angular by following a helpful tutorial. However, I have encountered an issue while attempting to set null to the User object once the user has logged out. Error: ER ...

Navigate through the overlay's content by scrolling

Objective: Looking to implement a scroll feature for long content. Issue: Not sure how to create a scroll that allows users to navigate through lengthy content. Thank you! function openNav() { document.getElementById("myNav").style.height = "1 ...

Instead of returning an object, the underscore groupBy function now returns an array

Currently, I am attempting to utilize underscore to create an array of entities that are grouped by their respective locations. The current format of the array consists of pairs in this structure { location: Location, data: T}[]. However, I aim to rearran ...

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

Tips for positioning dynamic high charts in a bootstrap row

I have implemented HighCharts for displaying charts on my website. Specifically, I am utilizing the chart type solidgauge. The charts are dynamic and I am looking to arrange them horizontally across the page. My goal is to align the charts in a layout sim ...

Issue with responsive design: Media queries not applying max-width

GOAL I want the content of my page to adjust to screen sizes that are smaller than 600px wide. ISSUE When using the responsive tool in Chrome, preset screen sizes like iPhone X do not apply media queries properly. Even manually adjusting the screen size ...

Utilizing Isotope JS on your Wordpress website

I'm in the process of integrating the .js plugin, Isotope, into my Wordpress installation. It should be positioned at the bottom of this page: To achieve this, I am referring to an example on codepen: https://codepen.io/desandro/pen/mEinp The script ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...

Conceal a Tag with CSS

Looking to conceal a label using CSS <p class="half_form "> <label for="property_bathrooms">Bathrooms (*only numbers)</label> <input type="text" id="property_bathrooms" size="40" class= ...

Encountering issues when verifying the ID of Angular route parameters due to potential null or undefined strings

Imagine going to a component at the URL localhost:4200/myComponent/id. The ID, no matter what it is, will show up as a string in the component view. The following code snippet retrieves the ID parameter from the previous component ([routerLink]="['/m ...

TypeScript and Angular: Error Encountered when Trying to Combine Two Arrays

I'm attempting to combine two arrays of the same type that are nested within a "parent" array. The end goal is to flatten the structure. Below is the code I have been using: ngOnInit() { this.Logs.getAllLogs() .subscribe(logs => { ...

Tips for deleting "Category: [category name]" in Wordpress

I have attempted various solutions found in previous threads, but none of them seem to work for me. Here is a screenshot I am looking to remove the text from the header in the category and only display [category name]. Can anyone assist me with this, ple ...

Creating a button for every individual row within a table using a combination of PHP and HTML

I need assistance with my current PHP and HTML code that generates buttons on each table row: <!DOCTYPE HTML> <h2 class="text-center">Consulta</h2> <br> <table class="table table-striped"> <tr class="in ...

Enhancing Ionic's functionality by including extra access control to permit origin in response headers

Dealing with the issue of Ionic/Angular adding extra access control allow origin to response headers. How can this be prevented? My Nginx server currently has CORS enabled add_header 'Access-Control-Allow-Origin' '*' always; add_header ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...

The media query targeting a specific max-width and below appears to be malfunctioning

So, I'm experiencing an issue where the browser I'm using doesn't seem to be picking up the styles I've set for a max-width of 960px and below. Can anyone provide insights into what might be causing this? Any assistance would be highly ...