Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

433
Views
¿Cómo puedo agregar una clase a un elemento al pasar el mouse?

Cómo agregar clase a un div cuando se desplaza sobre el div.

Modelo -

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

Componente -

 import {Component} from 'angular2/core'; @Component({ selector: 'hello-world', templateUrl: 'src/hello_world.html', styles: [` .red { background: red; } .yellow { background: yellow; } `] }) export class HelloWorld { }

Manifestación

[NOTA: específicamente quiero agregar una nueva clase y no modificar las clases existentes]

¡Suspiro! ¡Es un caso de uso tan normal y todavía no veo ninguna solución directa!

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Para no ensuciar el código, acabo de codificar una directiva hover-class simple.

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

Muestra corriente

Stackblitz del editor de código

Aquí debajo de la directiva,

 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); } }
about 4 years ago · Santiago Trujillo Report

0

También puedes usar algo como:

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

Luego en el componente

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

Plunker

Alternativamente, haga todo en el marcado:

 [ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"
about 4 years ago · Santiago Trujillo Report

0

Simple como abajo

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

DEMO EN VIVO

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!