I copied the Angular Material email example exactly. It has hint text and error text. My issue is that the error text overrides the hint text. How do I keep the hint text there?
If I try and change it to a simple span tag it messes up the control.
The Angular Material input
behavior follows the Material Design guidelines on text fields which states:
When input isn’t accepted, text fields can display an error message below the input line, with instructions on how to fix the error. Until the error is fixed, the error replaces the helper text.
You could add a custom error message container below the hint text using something like:
<div class="text-danger margin-bottom-thin my-mat-hint">
{{error}}<span> </span>
</div>
Where my-mat-hint
is defined as:
.my-mat-hint {
line-height: 1.2em;
transform: translateY(10px);
font-size: 75%;
}
The full context of the Material Design documentation is provided below.
Helper text gives context about a field’s input, such as how the input will be used.
It should be visible either persistently or only on focus.
When input isn’t accepted, text fields can display an error message below the input line, with instructions on how to fix the error. Until the error is fixed, the error replaces the helper text.
An error message should appear on a single line, if possible.
I agree with you. The error message will overlap the Hint. Here is what I do to solve the issue. I hide the Hint via CSS when there is an error related to the field and when the error is fixed, the style is automatically removed and the Hint shows up intact.
The way this happens is that Angular adds a class "mat-form-field-invalid" for every input element that has an invalid state. So we will use the class name to hide/show the hint for the invalid element.
Here is example code to solve the problem:
Form Field:
<mat-form-field>
<input matInput required
formControlName="materialName"
name="materialName"
id="materialName"
placeholder="Enter Material Name..."/>
<mat-hint align="start">Min 1</mat-hint>
<div class="error-message" *ngIf="error">Error</div>
</mat-form-field>
CSS:
This will hide the Hint whenever there is an error for a form field:
.mat-form-field-invalid .mat-hint {
display: none;
}
Show the Hint as well as the Error at the same time:
If you would rather show the Hint as well as the Error at the same time, then we just need to do a single style tweak. Instead of hiding the hint, we just add a margin to it so that it aligns itself from a distance, when Error occurs. So here is the revised style:
.mat-form-field-invalid .mat-hint {
margin-top: 20px;
}
Caveat: Make sure that the Hint is placed within the <mat-form-field></mat-form-field>
tags. If you place the Hint outside of these tags, then the above code won't work.
Good Luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With