Customize the css of the <td *matCellDef> within an Angular sidenav

 <th mat-header-cell id="tableHeader" *matHeaderCellDef> </th>
        <!-- Show headers-->
        <td mat-button id="dropDown" href="javascript:void()" (click)="element.isExpanded = 
        !element.isExpanded"
        *matCellDef="let element of docs"> {{element.name}}
        </td>
  </ng-container>

Is there a way to change the color of a specific 'element.name' when it is hovered or clicked? I am struggling to target only one element at a time, as my current method changes the color for all elements simultaneously. The data for this table comes from a JSON file and displays headers in a sidenav that can be clicked to reveal subheaders.

I specifically want to change the color of 'Administration' (=element.name) and its corresponding subheader, 'test', as shown in this image.

    <th mat-header-cell id="tableHeader" *matHeaderCellDef> </th>
    <!-- Show headers-->
    <td mat-button id="dropDown" href="javascript:void()" 
    (click)="element.isExpanded = !element.isExpanded"
    *matCellDef="let element of docs" [style.background- 
    color]="bkColor"> {{element.name}}
    </td>
    </ng-container>

The code snippet above is what I've used to change the background color of all cells. However, I would like to apply the color change only to the mat-buttons I click on and have them revert back to their original color when clicked again.

I tried using CSS by adding `#dropDown:hover` selector but it only changes the color temporarily while hovering. I need a permanent color change upon clicking.

My attempt to do it in TypeScript only affects the very first 'element.name'.

test() {
  var toggle = document.getElementById("dropDown");
  toggle.style.background = "red";
}

// The edited code below also failed to produce the desired result.

<td mat-button id="dropDown{{i}}" href="javascript:void()" (click)="element.isExpanded = !element.isExpanded"
      *matCellDef="let element of docs; index as i" (mouseenter)="changeColor(i)"> {{element.name}}
     </td>

In TypeScript:

 changeColor(index: number): void {
        const elem = document.getElementById('dropDown' + index);
        if (elem) {
          elem.style.backgroundColor = 'green';
        }
      }

Solution: For those using the multiTemplateDataRows property with mat-table set to true, you should use either dataIndex or renderIndex instead of index.

     <td
     mat-cell
     id="dropDown{{ i }}"
     *matCellDef="let element of docs; let i = dataIndex"
     href="javascript:void()"
     (click)="changeColor(i); element.isExpanded = 
     !element.isExpanded;">
       {{element.name}}
     </td>

Answer №1

Avoid duplicating elements with the same id attribute.

To fix this issue in your HTML code, make the following changes:

<td mat-button id="dropdown{{i}}" href="javascript:void()" 
(click)="element.isExpanded = !element.isExpanded"
*matCellDef="let element; index as i" [style.background- 
color]="bkColor" (mouseenter)="changeColor(i)"> {{element.name}}
</td>

Update your TypeScript file with the following:

changeColor(index: number): void {
const elem = document.getElementById('dropdown' + index);
if (elem) {
  elem.style.backgroundColor = 'green';
}

}

For a working example, check out this link.

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 utilize struts tags within HTML tags to set their attributes?

I have come across this code snippet but haven't tested it out yet: <input type="checkbox" id="<bean:write name="element" property="idvalue" />" /> Would this code work as intended? Additionally, are there more efficient ways to achieve ...

Is there a way for me to extract a file from the file system in React Native, convert it to base64, and then post it as JSON using HTTP

After following a helpful guide on audio and video recording in React Native from this informative article, I utilized the code available on Github here. The app I built allows users to record audio and save it to the file system. However, I encountered a ...

When attempting to send the token to the server using Angular's WWW-Authenticate: Bearer method, only to encounter a 401

I am a novice in Angular and I have developed a small role-based application using Angular 9 for the frontend and Asp.net core. Everything works fine when I log in or out of the app, and I can access non-Authorize controllers from the frontend without any ...

The Bootstrap modal-backdrop dilemma requiring JavaScript intervention

I am encountering some problems with the Bootstrap modal. When I try to open a modal, everything looks good, but when I close it, the screen turns completely black. Upon closer inspection, I found that every time I click on the X to close the modal, there ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Encountered a SyntaxError stating 'Unable to use import statement outside a module' while attempting to utilize three.js

I'm facing difficulties with incorporating three.js into my project. Initially, I executed: I am referring to the guidelines provided here: In my VS Code terminal for the project folder, I ran the following command: npm install --save three Subsequ ...

Resolving JSON/AJAX Problem Arising from Server Session Expiration

I've encountered a frustrating issue with my website where ajax and json calls are not working after the session timeout of 120 minutes on the server side. When a user attempts to make a call from a loaded page after the timeout, the call goes through ...

"Utilizing Flask to efficiently manage a multitude of buttons and seamlessly update a

I am working on a web application similar to mini-tweets. The content for the posts is retrieved from a database and I want to include an 'up vote' button for each post, similar to the image shown below. https://i.sstatic.net/kJySO.png Each pos ...

Delivering content through JSON instead of using AJAX

My Script: <script> jQuery(function($) { $('#payment-form').submit(function(event) { var $form = $(this); // Disable the submit button to prevent repeated clicks $form.find('input[type=submit]').attr('disabled& ...

Transform XML into HTML with XSLT

In my .net C# web application, I have an XML document that I want to display in a simple format similar to IE. It is important for the display to be consistent and browser-independent as much as possible. So far, I have tried embedding the XML document as ...

Using Internet Explorer 10 or 11 to run an Angular 8 application

Having trouble displaying my Angular 8 app on Internet Explorer 10 and 11. It currently only shows a blank white page with an empty component. I've followed various guides online and Stack Overflow answers like this one https://i.sstatic.net/sM6bL.pn ...

How can you get the selected option from a drop-down menu using JavaScript without using JQuery?

UPDATE: JSFiddle Link I'm facing some challenges with this task. I'm trying to keep my code clean without overusing unnecessary IDs or classes. The issue lies with a drop-down menu that offers speed options for displaying words in real-time on ...

Tips for updating the border color of a navigation tab

Struggling with changing the border color for Tab 2, while Tab 1 works fine. All my custom CSS comes after Bootstrap 5 CSS, so why isn't it overriding the changes? CSS .nav-tabs { border-color: black; } .nav-tabs > li > a { border-colo ...

retrieving information and parsing from an API using Ionic and Angular version 4

How can I extract data from the "data" field in my API using a function? getMenu() { return this.http.get('http://site.dev/api/menu/7'); } { "id": 26, "name": "Default", "title": "default", "pageelements": [ { "id": 15, ...

Determine if a collection of items in an array meets specific requirements

I've got a collection of objects similar to this: [{'type' :'car', 'color' : 'red', 'engine' : 'diesel'}, {'type' : 'truck'...} Now, I'm seeking a Python 3 approach ...

Issue encountered when transferring Angular app to Python Flask

Not sure what information to provide, but I will give as much detail as possible. Currently, my Angular app is running on IIS and utilizing Classic ASP. Everything is working smoothly. There is a dropdown that fetches JSON data to populate a table. Recen ...

Customizing Bootstrap styles with a custom CSS file

Currently, in my Django project, I am attempting to customize the base.html file which is utilizing the default bootstrap.min.css by replacing it with a custom.css file like so: base.html: <body id="bootstrap-overrides"> custom.css: #bootstrap-ov ...

Choosing items within a category

For quite some time now, a question has been bothering me. I've been delving deeper into CSS lately and have made the decision to avoid using jQuery in this Drupal project to stay clear of custom code. The issue arises with a class that is applied to ...

What is the best way to track events in angular-meteor when a user logs in, logs out, or when there is a change in the user

I am working on meteor-angular and trying to track new user login and logout changes within a single component. I have attempted to subscribe to userData in the component's initialization, but it does not seem to detect when the user logs in or out. I ...

Accordion content in motion

After creating an accordion, I wanted to enhance the user experience by adding a transition effect whenever they click on the accordion header. Even though I included height: auto and transition in the accordion container, it did not seem to have any impa ...