I am building angular app, and I am using ngFor directive to create a table for the employees. for the employee’s name, when I hover over it, I want this field to change its color (the hover over field only), I use(mouseenter) event binding to change the text color. the problem is when the mouse enters a specific employee name, all the employees names change their text color because of the ngFor directive instead of the specific field only, how can I solve it?
<table border="1">
<thead>
<tr>
<th>Employee Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
<td (mouseenter)="applyColor=true" (mouseleave)="applyColor=false"
[ngClass]="{'name-cell': applyColor}">{{ employee.name }}</td>
<td>{{ employee.department }}</td>
<td>{{ employee.salary }}</td>
</tr>
</tbody>
</table>
I tried to use inner span to include the styling but the same issue still exists.
2
Answers
The problem is that
applyColor
is a component-wide variable. When true,'name-cell': applyColor === true
will be true for each row. (I added=== true
for clarity).If you want to keep your approach, save the index of the hovered element:
Where hoveredIndex is:
You could try a simpler approach, using only css
hover
.In the component you just add a distinct class to the name cell (like:
<td class='your-class'>{{ employee.name }}</td>
and in the css you do your styling on.your-class:hover
, no need formouseenter
andmouseleave
.Here’s a working exemple on Stakblitz.