I have the following directive:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'd-btn',
host: {}
})
export class ButtonDirective {
constructor(private el: ElementRef){}
@HostListener('mouseover')
onm ouseOver() {
this.el.nativeElement.style.transition;
this.el.nativeElement.style.backgroundColor = "var(theme-color-1)";
}
@HostListener('mouseout')
onm ouseLeave() {
this.el.nativeElement.style.transition;
this.el.nativeElement.style.backgroundColor = 'transparent';
}
}
If instead of "var(theme-color-1)" I write a color it adds the given color when the user hovers over the element. But I would like to give it a variable color, because I am working on different color themes. Any ideas?
CodePudding user response:
The solution should be pretty easy and is not an Angular problem. You can solve this easily by CSS:
button[d-btn] {
transition: all .5s;
background: transparent;
}
button[d-btn]:hover {
transition: all .5s;
background: var(--theme-color-1);
}
CodePudding user response:
Couple of small things. To use a css variable you need to have -- in front of it.
@Directive({
selector: 'button[d-btn]'
})
export class MyButtonDirective {
constructor(private el: ElementRef){}
@HostListener('mouseover')
onm ouseOver() {
this.el.nativeElement.style.transition;
this.el.nativeElement.style.backgroundColor = "var(--theme-color-1)";
}
@HostListener('mouseout')
onm ouseLeave() {
this.el.nativeElement.style.transition;
this.el.nativeElement.style.backgroundColor = 'transparent';
}
}
Also make sure the same color is defined, e.g in style.css.
:root {
--theme-color-1: red !important;
}
Apply the directive to a button like so.
<button d-btn (click)="onClick($event)">Click Directive Button</button>
Here is an working example: https://stackblitz.com/edit/angular-button-1k8ycq?file=app/button.directive.ts
