I am trying to have mat-label text be in Red – having red font either part of a required field as input or select type fields. Input and Select fields have an attribute required. I would like the red font to be on page load and not after some user interaction.
Isn’t there something out of the box angular? This seems like a trivial thing should be available out of the box without tinkering with CSS, classes or do on focus on blur script call tricks.
So far I get the astricts but no red color.
<div class="row">
<div class="col-sm-6">
<mat-form-field [floatLabel]="'always'">
<mat-label>Select Your Car</mat-label>
<select matNativeControl id="mySelectId" required>
<option value="" disabled selected></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>
</div>
<div class="col-sm-6">
<mat-form-field [floatLabel]="'always'">
<mat-label>Select Your Mileage</mat-label>
<input id="mil" #mil
matInput name="mil"
placeholder="Mileage"
[(ngModel)]="model.mil"
required>
</mat-form-field>
</div>
</div>
Desired Result:
To achieve the desired effect of having the mat-label text in red color for required fields on page load, you can use Angular’s built-in functionalities along with a small amount of CSS. Unfortunately, there isn’t an out-of-the-box Angular Material feature that directly supports this specific styling requirement.
However, you can accomplish this with a few simple steps:
Add a class to your required fields:
Apply a custom class to mat-form-field if the input/select field is required.
Define CSS for the custom class:
Use CSS to change the color of the mat-label to red.
Here’s how you can implement it:
HTML Template:
Add a custom class (required-field) to your mat-form-field elements that have required fields:
<div class="row">
<div class="col-sm-6">
<mat-form-field class="required-field" [floatLabel]="'always'">
<mat-label>Select Your Car</mat-label>
<select matNativeControl id="mySelectId" required>
<option value="" disabled selected></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</mat-form-field>
</div>
<div class="col-sm-6">
<mat-form-field class="required-field" [floatLabel]="'always'">
<mat-label>Select Your Mileage</mat-label>
<input id="mil" #mil
matInput name="mil"
placeholder="Mileage"
[(ngModel)]="model.mil"
required>
</mat-form-field>
</div>
</div>
CSS:
Define the styles for the custom class to change the mat-label color to red:
/* Add this CSS to your global styles.css or the component-specific CSS file */
.required-field mat-label {
color: red;
}
Asim Ali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1