How can I add a class to an element on hover?

Ajey picture Ajey · Mar 6, 2017 · Viewed 60.3k times · Source

How to add class to a div when hovered on the div.

Template -

<div class="red">On hover add class ".yellow"</div>

Component -

import {Component} from 'angular2/core';

@Component({
  selector: 'hello-world',
  templateUrl: 'src/hello_world.html',
  styles: [`
    .red {
      background: red;
    }

    .yellow {
      background: yellow;
    }

  `]
})
export class HelloWorld {
}

Demo

[ NOTE - I specifically want to add a new class and not modify the existing classes ]

Sigh! It is such a normal use case and I do not see any straight forward solution yet!

Answer

Dylan picture Dylan · Mar 6, 2017

You can also just use something like:

[ngClass]="color" (mouseover)="changeStyle($event)" (mouseout)="changeStyle($event)"

Then in the component

color:string = 'red';

changeStyle($event){
  this.color = $event.type == 'mouseover' ? 'yellow' : 'red';
}

Plunker

Alternatively, do everything in the markup:

[ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"