How can CSS variables be applied to a hover property within an Angular directive?

Check out the directive below:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'd-btn', 
  host: {}
})

export class ButtonDirective {
    constructor(private el: ElementRef){}
    @HostListener('mouseover')
    onMouseOver() {
        this.el.nativeElement.style.transition;
        this.el.nativeElement.style.backgroundColor = "var(theme-color-1)";
    }
    
  
    @HostListener('mouseout')
    onMouseLeave() {
        this.el.nativeElement.style.transition;
        this.el.nativeElement.style.backgroundColor = 'transparent';
    }
}

If I replace "var(theme-color-1)" with a specific color value, it works fine when hovering over the element. However, I would like to use a variable color instead since I am working on multiple color themes. Any suggestions?

Answer №1

Solving this issue should not be difficult and is unrelated to Angular. You can resolve it simply by utilizing CSS:

button[d-btn] {
  transition: all .5s;
  background: transparent; 
}
button[d-btn]:hover {
  transition: all .5s;
  background: var(--theme-color-1); 
}

Answer №2

Just a few minor details to keep in mind. When using a css variable, remember to include -- before the variable name.

@Directive({
  selector: 'button[d-btn]'
})
export class MyButtonDirective {
  constructor(private el: ElementRef){}
  @HostListener('mouseover')
  onMouseOver() {
      this.el.nativeElement.style.transition;
      this.el.nativeElement.style.backgroundColor = "var(--theme-color-1)";
  }
  

  @HostListener('mouseout')
  onMouseLeave() {
      this.el.nativeElement.style.transition;
      this.el.nativeElement.style.backgroundColor = 'transparent';
  }
}

Also, ensure that the same color is defined in your style.css file.

:root {
  --theme-color-1: red !important;
}

To apply the directive to a button, use the following syntax:

<button d-btn (click)="onClick($event)">Click Directive Button</button>

If you'd like to see a working example, check out this link: https://stackblitz.com/edit/angular-button-1k8ycq?file=app%2Fbutton.directive.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The datatable only accepts arrays and Iterable data types

While attempting to perform a CRUD operation with the datatable, I encountered an error message "Only arrays and iterables are allowed in datatable" upon clicking the submit button for creation. The console pointed out the error in the component.html file ...

Tips for automatically creating a categoryId using ObjectId for a category in Nest JS, Typescript, and Mongoose

book.entity.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import mongoose, { Document } from 'mongoose'; import { Category } from 'src/category/entities/category.entity'; export type BookDocument = Book & ...

Is it possible to implement cross-field validation with Angular 2 using model-based addErrors?

Currently, I am working on implementing cross-field validation for two fields within a form using a reactive/model based approach. However, I am facing an issue regarding how to correctly add an error to the existing Error List of a form control. Form: ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Ways to set a default value for a union type parameter without encountering the error "could be instantiated with a different subtype of constraint"

After referring to my recent inquiry... Can a default value be specified for valueProp in this scenario? type ValueType = 'value' | 'defaultValue' type Props<T extends ValueType> = Record<T, string> ...

Differences between Pipe and Tap when working with ngxsWhen working with

While experimenting with pipe and subscribe methods, I encountered an issue. When using pipe with tap, nothing gets logged in the console. However, when I switch to using subscribe, it works perfectly. Can you help me figure out what I'm doing wrong? ...

While trying to update Angular 5 to 6, I am encountering an incompatible peer dependency error when utilizing the ng update @angular/core command

I have been encountering issues while trying to upgrade my Angular app from version 5 to version 6 by following this guide. After successfully running the commands below: npm install -g @angular/cli npm install @angular/cli ng update @angular/cli An err ...

Tips on sending a list via @Input using Angular5

I was seeking guidance on how to pass a list through an input. In my parent component, I have the following: list: Hero[] = [{Id: 2, Name: "Sll"}, {Id: 3, Name: "Sldsadasd"}] and in the HTML: <app-add-hero list="{{list}}" hero={{hero}}></app-ad ...

Ways to utilize array reduce for organizing information

Can someone please guide me on how to use the reduce array method to sort entries by date in the following data: const entries = [ {date: 'lu'}, {date: 'lu'}, {date: 'ma'}, {date: 'ma'} ] I would like the ou ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

Event triggered by an Angular counter

Typescript: countdown; counter = 10; tick = 1000; this.countdown = Observable.timer(0, this.tick) .take(this.counter) .map(() => --this.counter) Also in HTML: <div> <h1>Time Remaining</h1> <h2>{{countdow ...

The Angular2 application was constructed using angular-cli, incorporating a directive, and optimized with the ng build

I am working on an angular-cli app and my environment details are: npm -v 3.10.8 node -v v6.9.1 angular2 ^2.4.0 angular/cli 1.0.0-beta.32.3 Recently, I added the following line to my package.json: "angular2-auto-scroll": "1.0.12" You can find more info ...

Incorporating an expansion panel within an Angular Material table row

I'm currently working on incorporating an expansion panel, possibly a new component, similar to the mat-accordion. This will allow for a detailed view to be displayed within a mat-table row upon clicking. To better illustrate this requirement, I have ...

Issue with PrimeNG overlaypanel displaying error message "Functionality of this.engine.setProperty is not available"

After importing OverlayPanelModule as @NgModule in parent.module.ts, I added the following code in child.component.html: <p-overlayPanel [dismissable]="false" #overlay> Content </p-overlayPanel> However, upon testing, I encountered the error ...

Error with Background component in Next.js-TypeScript when trying to change color on mouseover because Window is not defined

Within my Background component, there is a function that includes an SVG which changes color upon mouseover. While this functionality works fine, I encountered an error when hosting the project using Vercel - "ReferenceError: window is not defined." This i ...

Using TypeScript: Union Types for Enum Key Values

Here's the code in the TS playground too, click here. Get the Enum key values as union types (for function parameter) I have managed to achieve this with the animals object by using key in to extract the key as the enum ANIMALS value. However, I am s ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

Filtering Columns in Angular2 DataTable

Is there a way to filter an entire column, including the header and data, using Angular2 data-table? I have figured out how to filter the column data, but the header remains unaffected: https://stackblitz.com/edit/data-table-filter-columns UPDATE: Afte ...

Tips for customizing the default styles of PrimeNG's <p-accordion> tag

Hello, I have encountered an issue with my html code snippet. I am attempting to create a tab with a label-header named "Users", but the accordion tag consistently displays it as underlined. <div class="ui-g"> <p-accordion id="tabsHeader"> ...

Tips on accessing validator errors in Angular

Is there a way to extract the value from the 'minLength' validator error in order to use it in a message? This is my current HTML setup: <div class="mt-2" *ngIf="ngControl.control.errors?.minlength"> {{ &ap ...