'Using CSS hover property in Angular directive?
Here is the directive, the default one.
import { Directive, Input, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[newBox]'
})
export class BoxDirective {
@Input() backgroundColor = '#fff';
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit(): void {
this.renderer.setStyle(this.el.nativeElement, 'background-color', this.backgroundColor);
}
}
Now, on hover, I want the background-color to change. How do I do that in the directive?
Solution 1:[1]
use HostListener
to listen to events
@HostListener('mouseover')
onMouseOver() {
this.backgroundColor = '#fff';
}
@HostListener('mouseout')
onMouseOut() {
this.backgroundColor = '#000';
}
Solution 2:[2]
import { Directive, ElementRef, HostListener, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective implements OnInit {
@HostListener('mouseenter') onMouseEnter(){
this.renderer2.setStyle(this.elRef.nativeElement,'fontSize','100px')
this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
}
@Input('appHover') case:string='';
@HostListener('mouseout') onMouseOut(){
this.renderer2.setStyle(this.elRef.nativeElement,'fontSize',this.case)
this.renderer2.setStyle(this.elRef.nativeElement,'color','#fff')
this.renderer2.setStyle(this.elRef.nativeElement,'backgroundColor','orange')
}
constructor(private elRef:ElementRef,private renderer2:Renderer2) { }
ngOnInit(): void {
}
}
goto app.component.html
then use directive.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sachila Ranawaka |
Solution 2 | B.K tech_Info |