<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>