Customizing Material Radio Buttons
Text Color Customization
According to Angular's API, the ng-deep psuedo-class is considered as deprecated and it completely disables view-encapsulation for that particular rule.
Using it without the :host pseudo-class will make the style-rule global, which may not be ideal. This is commonly suggested by Angular when there are no other alternatives available at the moment.
If you want to apply the styles globally, you can simply include them in the styles.scss
.
.mat-radio-button {
color: pink;
}
Alternatively, if you wish to use a color from your palette:
.mat-radio-button {
color: mat.get-color-from-palette($primary-light, 400);
}
However, if you want to apply it specifically to a certain radio-button within some.component.scss
, you can utilize ::ng-deep
, while ensuring to use the :host
pseudo class to prevent the rule from affecting other components:
:host ::ng-deep .mat-radio-button {
color: #556EE6;
}
In summary, knowing the correct class names to override is crucial. In some cases like the ripple, the use of !important
may be necessary to override the default settings.
The Role of !important
Some individuals prefer to customize the ripple effect with a secondary or off-color. Let's consider that as an example:
.mat-radio-ripple .mat-ripple-element {
background-color: mat.get-color-from-palette(
$accent-palette,
A400
) !important;
}
For such scenarios, or any other styles you have already modified in your styles.scss
, adding !important
becomes essential.
Applying Styles to Select Tags Only
In situations where only select groups/radio-buttons should receive the styling, you can introduce an additional class selector.
Template:
<li>
<mat-radio-group
class="pink"
aria-label="Select an option"
formControlName="gender"
>
<mat-radio-button color="primary" value="male">Male</mat-radio-button>
<mat-radio-button value="female">Female</mat-radio-button>
</mat-radio-group>
</li>
CSS:
.pink .mat-radio-button {
color: pink;
}
Or for customizing just one of the radio buttons:
<div class="pink">
<mat-radio-button value="female">Female</mat-radio-button>
</div>
Dynamic Application of Styling Based on Condition
Another scenario involves applying styles dynamically based on specific conditions.
Template:
<div [ngClass]"getClass()">
<mat-radio-button value="female">Female</mat-radio-button>
</div>
Script:
getClass(event: Event) {
if(/* Your conditions */)
return ['pink']
return []
}
Explore on Stackblitz
Feel free to check out a Material Form Example on my Stackblitz account showcasing the concepts mentioned above (and more), along with a Material Theme implementation. In this demo, I've overridden the mat-radio-button globally in styles.scss
and also in app.component.scss
.