This question has a Stackblitz based on the Angular documentation, Validating input in reactive forms. Given a simple Angular form with validation:
How can I stop the form from jumping around when displaying error messages?
For example, upon entering an invalid email address, the password field is pushed down to make way for the error message. In the same way the login button is pushed down when the password validation fails.
I have previously used Angular Material Form Fields which has its own way of reserving space for validation messages.
I understand that I need to reserve some space for the error message, but how should this be achieved? Two ideas I've rejected so far:
The HTML code for conditionally displaying error messages is
<form [formGroup]="form" fxLayout="column" fxLayoutGap="24px">
<!-- Email -->
<div>
<label for="email">Email</label>
<input id="email" formControlName="email">
<!-- Errors -->
<div *ngIf="email.invalid && email.dirty" class="warn">
<div *ngIf="email.errors.required">Email is required</div>
<div *ngIf="email.errors.email">Must be a valid email address</div>
</div>
</div>
<!-- Password -->
<div>
<label for="password">Password</label>
<input id="password" type="password" formControlName="password">
<!-- Errors -->
<div *ngIf="password.invalid && password.dirty" class="warn">
<div *ngIf="password.errors.required">Password is required</div>
</div>
</div>
<!-- Button -->
<button class="submit">Login</button>
</form>
One way to deal with this is to make the div
wrapping the errors have a height so it is always on the screen and the error messages inside it appear conditionally.
<div class="warn">
<ng-container *ngIf="email.invalid && email.dirty">
<div *ngIf="email.errors.required">Email is required</div>
<div *ngIf="email.errors.email">Must be a valid email address</div>
</ng-container>
</div>
.warn {
color: #FF3636;
font-size: 14px;
text-align: right;
height: 16px;
}
Now the warn
div is on the page, taking up 16px and just waiting to contain a message should validation fail.
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