Search code examples
angulardynamiccolorsslidertailwind-css

Angular & Tailwind - Dynamically change the colour of a slider thumb?


I have been trying for a whole day now to try and change the colour of the accent/thumb/control of a slider and I cannot seem to get it right. It's easy to set a colour if you're not planning on dynamically changing the colour of it at any point (for instance, a user changing its colour using a colour selector).

Using Angular 14 & TailwindCSS.

My current solution makes use of the selector [&::-webkit-slider-thumb], which works fine if you just want to set the colour and call it a day. I've tried using [ngClass] but the colour just doesn't update no matter what I try.

I have also tried making a function that looks like this:

public get sliderClasses(): string {
    return `[&::-webkit-slider-thumb]:bg-[${this.primary}] [&::-webkit-slider-thumb:active]:bg-[${this.secondary}]`;
}

Primary & Secondary are just hex codes e.g #FF0000

Trying to use this on [ngClass], it also does nothing. Any ideas?


Wongjn's Suggestion:

I have just tried this solution suggested by @Wongjn, however there's no value in --primary so the background is just transparent. Using a simple button to test the solution.

<input type="button" value="Submit" [style]="{'--primary': '#000'}" class="bg-[--primary]">

Working Solution:

This is the correct solution but needed a little bit of editing, below is the working solution, thanks to @Wongjn!

<input type="button" value="Submit" [style]="{'--primary': '#000'}" class="bg-[var(--primary)]">

Solution

  • As per the documentation:

    The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.

    If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS:

    Don’t construct class names dynamically

    <div class="text-{{ error ? 'red' : 'green' }}-600"></div>
    

    In the example above, the strings text-red-600 and text-green-600 do not exist, so Tailwind will not generate those classes. Instead, make sure any class names you’re using exist in full:

    Always use complete class names

    <div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
    

    You could consider using the style attribute like:

    @Component({
      template: `
    <div
      [class]="sliderClasses"
      [style]="{
        '--primary': primary,
        '--seconday': secondary
      }"
    >…</div>`,
    })
    
    export class Component {
      primary = '#f00';
      secondary = '#0f0';
      public get sliderClasses(): string {
        return "[&::-webkit-slider-thumb]:bg-[--primary] [&::-webkit-slider-thumb:active]:bg-[--secondary]";
      };
    }