Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Select: change color of disabled option

Using Angular/Material 6.2, cannot find the right CSS setting to override the color of a selected mat-option within a disabled mat-select:

<mat-select [disabled]="true" [value]="option2">
  <mat-option>None</mat-option>
  <mat-option value="option1">Option 1</mat-option>
  <mat-option value="option2">Option 2</mat-option>
  <mat-option value="option3">Option 3</mat-option>
</mat-select>

The following is not doing it in my app's styles.css (the default is too faded; I need it more emphasized in my app):

.mat-select-disabled, .mat-select-content, .mat-disabled, mat-select.mat-disabled {
  opacity: 1.0 !important;
  font-weight: bold !important;
  color: black !important;
}

Search for workarounds yields several suggestions I can't get to work in this rapidly changing API. It's quite possible I'm css-ignorant, but I'm finding small styling changes harder than expected with Material.

like image 739
Ped Avatar asked Jan 01 '23 19:01

Ped


1 Answers

If you inspect the generated CSS for the mat-select element, you'll find that the .mat-disabled class doesn't style <mat-select> directly. Instead, its descendants change styling based on the presence of that class; namely, the trigger value (the element with the most visual styling applied to it) has a specificity rule of

.mat-select-disabled .mat-select-value {
    color: rgba(black, 0.38);
}

(side note -- I see you're using opacity: 1 in your example rule. That won't make text with a color: rgba(x) look any different.)

Just by nature of CSS you'll need to get more specific than this rule to override it.

Because Angular is awesome, it operates on a concept called view encapsulation -- a component's styles are local to that component. This is achieved with an attribute tag, where all components styles will have that added to selectors as a rule.

This means that if you just copy that same rule in your component, it will be more specific than the previous selectors and will apply.

If you're trying to apply this globally, you'll need to add another class selector and add that class to the element. Or, those using SASS and Material theming could wrap this up in a theme and apply it with a simple class. A directive would work too.

Also, please please never use !important. A puppy dies every time you do.

like image 93
joh04667 Avatar answered Jan 13 '23 10:01

joh04667