Changing the Row's Background Color in Angular When the Button is Clicked

My code includes a list where each row has a button to open a sidebar. Due to the large number of elements in the list, I want the background color of the row to turn yellow when the button is clicked, as a way to indicate what has been selected. Currently, when I click the button, the entire list turns yellow. How can I resolve this issue and achieve the desired behavior?

HTML:

<div class="content">
    <div fxLayout="row">
        <!-- CONTENT -->
        <div fxFlex class="px-8" fxLayout="column" fusePerfectScrollbar>

            <div fxLayout="column" fxLayoutAlign="end" class="mat-elevation-z4 responsive-grid">
                <div fxLayout="row" fxLayoutAlign="end" class="pr-4">
                    <mat-form-field fxFlex fxFlex.gt-sm="30">
                        <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filtrele">
                    </mat-form-field>
                </div>
                <table mat-table [dataSource]="dataSource" matSort class="stock-table" id="pool-row">
                    <ng-container matColumnDef="Reference">
                        <th mat-header-cell *matHeaderCellDef mat-sort-header>
                            Reference </th>
                        <td mat-cell *matCellDef="let row; let i = index">
                            <p *ngIf="controlReferanceColor(row)" style="color:red;">{{row.Reference}}
                            </p>
                            <p *ngIf="!controlReferanceColor(row)">{{row.Reference}}</p>
                        </td>
                    </ng-container>
                    <ng-container matColumnDef="Actions">
                        <th mat-header-cell *matHeaderCellDef></th>
                        <td mat-cell *matCellDef="let row">
                            <a mat-icon-button matTooltip="Detay" *ngIf="row.SourceType?.Id != 32"
                                [routerLink]="getLink(row)" target="_blank">
                                <mat-icon>open_in_browser</mat-icon>
                            </a>
                            <button mat-icon-button matTooltip="Liste" *ngIf="row.SourceType?.Id == 32" id="list"
                                class="sidebar-toggle" (click)="getReferenceList('lab-test-d...

TS:

getReferenceList(sidebarName: string, reference: IProcess) {
    if (reference && reference.Reference != "") {
        this.selectedProcessList = this._stockService.processList.find(
            (x) => x.Reference === reference.Reference
        ).ChildProcessList;
        this._fuseSidebarService.getSidebar(sidebarName).open();
        document.getElementById('pool-row').style.backgroundColor = '#fced49';
    }
}
openSidebar(name: string, stockEntryId: number): void {
    //this.previewStockEntryId = stockEntryId;
    this._fuseSidebarService.getSidebar(name).open();
   
}

Answer №1

If you're working with Material tables and your data source objects have unique record identifiers, this suggestion may be helpful for setting CSS styles for selected and unselected table rows.

To achieve this, you can define CSS styles for selected and unselected rows:

CSS

.selectedClass
{
    background-color: yellow;
}

.unselectedClass
{
    background-color: beige;
}

In your HTML template, use the [ngClass] directive to conditionally apply these styles to each table cell based on the selected row:

HTML

...
<td mat-cell *matCellDef="let row" 
    [ngClass]="{ 'selectedClass': element.selectedRow === element.id, 
             'unselectedClass': element.selectedRow !== element.id }">
    <a mat-icon-button matTooltip="Details" *ngIf="row.SourceType?.Id != 32"
            [routerLink]="getLink(row)" target="_blank">
                <mat-icon>open_in_browser</mat-icon>
    </a>
    <button mat-icon-button matTooltip="List" 
        *ngIf="row.SourceType?.Id == 32" id="list"
        class="sidebar-toggle" 
        (click)="getReferenceList('lab-test-detail-preview',row)">
        <mat-icon>pageview</mat-icon>
    </button>
</td>

In your TypeScript source, make sure to add a selectedRow property to your data source structure:

TS

export interface DataSource
{
  id: number;
  reference: string;
  actions: string;
    ...
  selectedRow: number;
}

Within your event handler, reset all selectedRow values to zero and set the selectedRow value for the currently selected object to its record id:

getReferenceList(action: string, row: DataSource)
{
    ...
    this.dataSource.map(e => { e.selectedRow = 0 });
    row.selectedRow = row.id;
    ...
}

By following these steps, you can apply the selected and unselected styles to table rows based on the currently selected row. Make sure to apply the conditional class to each table cell column to update the entire row's style accordingly.

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

Develop three.js elements using the map function

A function was created using react-three-fiber to display a butterfly loaded from a glb file with animation. The butterfly is enclosed in a primitive object passed as a prop. The structure is as follows: the butterfly is nested in a mesh, which is nested i ...

By default, make the initial element of the list the selected option in an AngularJS select input

I'm running into an issue with setting the first element in my ng-repeat list within a select input. Here is the code snippet causing the problem: <div> <span >OF</span> <select ng-model="eclatementCourante.ordreFabricationId" n ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

At a specific media query breakpoint, links are disabled while the rest continue to function without any

Today I encountered a puzzling issue on my website with a responsive layout that utilizes @media queries and breakpoints. At one specific breakpoint (or resolution, as I am still learning the terminology), the links in the navigation bar are inexplicably d ...

What is the best way to achieve this effect with CSS?

Is there a way to create this design with CSS? I experimented with applying border CSS and rotating the DIV, but couldn't quite achieve the desired result. Here is an image for reference: https://i.stack.imgur.com/yW6wK.png ...

Can a JavaScript class have a property that returns an array?

To those more experienced in node red development, this may be obvious, but I'll ask anyway. Within my node red flow, I have a function node containing a javascript class that only exposes static members. Here's an example: class MeasurementsLis ...

Ways to eliminate the dynamically included angular files from the .net core web api project

Embarking on a new project, I aim to utilize asp.net core web.api and angular 9. My initial goal is to establish a .net core web api project without MVC or scaffolded angular project. What I desire is to have the spa launch along with the web.api, mirrorin ...

Creating a ToggleButton in C#Is a Togglebutton the

I am trying to create a togglebutton for a website with Microsoft Visual Studio and am not sure if this would be the correct code to apply. I am working in C#, so the button is going to be generated in C# (and a bit of jquery) code and eventually styled in ...

Looking for a specific search term within the middle of strings in an array

Is there a way to improve the autocomplete feature of my input field so that it shows suggestions based on any part of the word typed in? I currently have it set up to only show suggestions if the input matches the start of a word in the array. How can I m ...

Bootstrap 4 input fields extend past padding boundaries

I have created a basic form using the following code: <div class="container"> <div class="jumbotron" style="width:100%"> <h1> ConfigTool Web Interface </h1> <p> Edit the con ...

Polymer element created specifically for this project can be seen in the DOM, yet it does not display any content within the

Snippet: <link rel="import" href="../../../../bower_components/polymer/polymer.html"> <link rel="import" href="../../../../bower_components/app-layout/app-drawer-layout/app-drawer-layout.html"> <dom-module id="app-index"> <templa ...

Upload a user-sent image to a remote SFTP server for safekeeping

Can someone help me figure out how to upload a file to an SFTP remote server using ssh2-sftp-client? I am trying to retrieve the file from the user via a post request along with the destination. To process the file, I am utilizing multer. const Client = r ...

The hidden pop-up window from a particular tool is currently not being displayed

I attempted to upload my code onto Stackblitz in search of assistance with my dynamic modal not displaying. I am working on a function that I intend to be able to call from any component to create a popup where I can dynamically modify the header, body, an ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

The 'toBeInTheDocument' property is not found on the 'Matchers<HTMLElement>' type

Having trouble setting up testing for a components library. Despite trying various examples and similar threads, I have not been successful. I can confirm that my setupTests.ts file is being loaded correctly (verified through a console.log). Additionally, ...

Utilizing MSAL's loginRedirect within an Ngrx Effect: A step-by-step guide

Is there a way to utilize Msal angular's loginRedirect(): void function instead of loginPopup(): Promise in an Ngrx Effect? I've been able to successfully implement the loginPopup() method, but since loginRedirect() has a void return type, it di ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...