问题
I'd like to change the color of the mat-slider background based on the value, i.e. each value has an associated color.
I see that I can override the background-color like so:
::ng-deep .mat-accent .mat-slider-track-fill {
background-color: red;
}
But how might I set it dynamically?
回答1:
I would create CSS classes for each value/color, then use a dynamic container ID to override the child slider's CSS classes.
HTML
<div id="{{'container-' + slider.value}}">
<md-slider #slider min="1" max="5" step="1" value="1"></md-slider>
</div>
CSS
#container-1 /deep/ .mat-accent .mat-slider-track-fill {
background: red!important;
}
#container-2 /deep/ .mat-accent .mat-slider-track-fill {
background: blue!important;
}
#container-3 /deep/ .mat-accent .mat-slider-track-fill {
background: green!important;
}
#container-4 /deep/ .mat-accent .mat-slider-track-fill {
background: yellow!important;
}
#container-5 /deep/ .mat-accent .mat-slider-track-fill {
background: purple!important;
}
Example stackblitz: https://angular-material-p9y14r.stackblitz.io
回答2:
I would create CSS classes for each value/color, then use ngClass to dynamically assign.
HTML
<div id='container' [ngClass]="['slider-bg-' + slider.value]">
<md-slider #slider min="1" max="5" step="1" value="1"></md-slider>
</div>
CSS
.slider-bg-1 {
background-color: red;
}
.slider-bg-2 {
background-color: blue;
}
.slider-bg-3 {
background-color: green;
}
.slider-bg-4 {
background-color: yellow;
}
.slider-bg-5 {
background-color: purple;
}
Example stackblitz: https://angular-material-dfpafj.stackblitz.io
来源:https://stackoverflow.com/questions/53710310/mat-slider-dynamic-background-color