Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

angular - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
  }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...