Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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!

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Not to dirty the code I just coded simple hover-class directive.

<span hover-class="btn-primary" class="btn" >Test Me</span>

Running Sample

Code Editor stackblitz

Here below the directive,

import { Directive, HostListener, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[hover-class]'
})
export class HoverClassDirective {

  constructor(public elementRef:ElementRef) { }
  @Input('hover-class') hoverClass:any;  

  @HostListener('mouseenter') onMouseEnter() {
    this.elementRef.nativeElement.classList.add(this.hoverClass);
 }

  @HostListener('mouseleave') onMouseLeave() {
    this.elementRef.nativeElement.classList.remove(this.hoverClass);
  }

}
over 4 years ago · Santiago Trujillo Denunciar

0

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'"
over 4 years ago · Santiago Trujillo Denunciar

0

Simple as below

<button [class.btn-success]="mouseOvered" 
  (mouseover)="mouseOvered=true"
  (mouseout)="mouseOvered=false"> Hover me </button>

LIVE DEMO

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda