mat-slider dynamic background color

本小妞迷上赌 提交于 2020-03-05 03:54:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!