在mat-select中更改所选值的样式

时间:2019-07-26 02:59:16

标签: css angular material

我在角度7中使用了mat-select,该选择由一组提供服务的颜色构成,我需要在选择颜色时显示所选颜色框而不是字符串。示例:

[在此处输入图片描述] [1] [在此处输入图片描述] [2]

我将在此链接中找到答案,但是从CSS进行修改对我不起作用

How to change the style in Angular 5 material mat-select selected text when disabled

1 个答案:

答案 0 :(得分:0)

这不是最优雅的方法,但可以解决问题!还有其他想法吗?

enter image description here

enter image description here

color.component.ts:

getSelectedColor(selected) {
  this.colorValue = selected.value;
}

color.component.scss:

div {
  width: 100px;
  height: 15px;
  margin: 0px auto;
}

.selected-color {
  position: absolute;
  bottom: 7px;
  left: 36px;
}

color.component.html:

<mat-form-field>
  <mat-select [formControl]="colorForm" (selectionChange)="getSelectedColor($event)" name="color" required>
    <mat-option *ngFor="let color of colors" [value]="color.value">
      <div [ngStyle]="{'background-color':color.value}"></div>
    </mat-option>
  </mat-select>
  <div class="selected-color" [ngStyle]="{'background-color':colorValue}"></div>
  <mat-error *ngIf="colorForm.hasError('required')">Please choose an color</mat-error>
</mat-form-field>