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!
To add a class to an element rather than replacing its existing classes, use the += operator instead. Note, it is important to prefix the new classname with space; otherwise, one of the existing classes of an element is lost.
CSS – Div class hover Hover effect can be directly given to the elements but when it is applied to a particular element like div then the hover effect will be reflected to all the div elements. Using a class to apply the hover effect, gives us a choice to apply it on selective elements.
hover(function () { $("li#rs1"). addClass("active"); //Add the active class to the area is hovered }, function () { $("li#rs1"). addClass("not-active"); }); });
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); } }
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'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With