Vulcano
Vulcano

Reputation: 435

Set the html slider background programmatically in angular2

I want to create a custom slider component, where the background color should be set with angular data binding.

Here is a simple stackblitz example where the default color green should be overridden/exchanged with the data-bound color red.

What I tried:

Question

Upvotes: 1

Views: 203

Answers (2)

Aslam
Aslam

Reputation: 9662

You can use the power of css variables.

CSS

.slider{
  --bg: green;
}

::-webkit-slider-runnable-track {
  background:var(--bg);
}

::-ms-track {
  background: var(--bg);
}

::-moz-range-track {
  background: var(--bg);
}

HTML:

Set {{color}} as background for this slider:
<br />
<div class="slider" [attr.style]="sanitizer.bypassSecurityTrustStyle('--bg:' + color)">
    <input id='slider' type="range">
</div>

Here is the implementation: https://stackblitz.com/edit/angular-oygzgp

Upvotes: 1

Poldo
Poldo

Reputation: 1932

You can use ngClass to set your color dynamically

in your css.

.test::-webkit-slider-runnable-track {
  background: red ;
}

.test::-ms-track {
  background:red ;
}

.test::-moz-range-track {
  background: red ;
}

in your html:

<input id='slider' type="range" [ngClass]="isRed ? 'red' : 'green'">

Upvotes: 0

Related Questions