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 { }[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!
Para no ensuciar el código, acabo de codificar una directiva hover-class simple.
<span hover-class="btn-primary" class="btn" >Test Me</span>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); } }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'; }Alternativamente, haga todo en el marcado:
[ngClass]="color" (mouseover)="color='yellow'" (mouseout)="color='red'"Simple como abajo
<button [class.btn-success]="mouseOvered" (mouseover)="mouseOvered=true" (mouseout)="mouseOvered=false"> Hover me </button>