Reputation: 2610
I have this reactive form input that I want to add a green or red bottom-border
to depending on its validation. In the below example I only have the validation required and when an input is touched and is invalid I want to add the class .invalid-input { bottom-border: 3px solid red}
. I tried the below code, but it isn't working. When I leave the input blank and move away to another input it doesn't show any border. Can someone see why?
<input
id="firstName"
class="form__input"
type="text"
placeholder="First Name"
(keyup.enter)="getErrors()"
formControlName="firstName"
ngClass="{
'invalid-input': firstName.invalid && (firstName.dirty || firstName.touched)
}"
>
CSS
.valid-input {
border-bottom: 3px solid green;
}
.invalid-input {
border-bottom: 3px solid red;
}
Upvotes: 1
Views: 14862
Reputation: 1644
To solve the issue what I've done is two things: 1. Mark the form as submitted using the following:
<form [ngClass]="{submitted:myForm.submitted}">
Add css for all the invalid input fields within the form:
form.submitted .ng-invalid { border:1px solid #f00; }
I hope it will help someone who experience similar issue.
Upvotes: 0
Reputation: 24404
You dont need to use ngClass directive angular reactive form add class to any reactive form control so you can easy target the state of the element.
.ng-invalid.ng-touched , .ng-invalid.ng-dirty{
border-bottom: 3px solid red;
}
in you question you need to use [ngClass]="..." and use
formGroup.controls.firstName
form control instant
Upvotes: 4
Reputation: 11982
it's not good idea to add class directly to input field but:
<div [ngClass]="{'invalid-input': formGroup.controls.firstName.invalid && (formGroup.controls.firstName.dirty || firstName.touched)}">
<label for="firstName">
First Name
<span class="required" aria-required="true"> * </span>
</label>
<input
id="firstName"
class="form__input"
type="text"
placeholder="First Name"
(keyup.enter)="getErrors()"
formControlName="firstName" >
</div>
Upvotes: 3
Reputation: 9764
Try like this
<div [ngClass]="{'invalid-input': firstName?.invalid && (firstName?.dirty || firstName?.touched)}"> This is test </div>
or
<div [ngClass]="{'invalid-input': firstName && (firstName.invalid && (firstName.dirty || firstName.touched))}"> This is test </div>
Upvotes: 1
Reputation: 41387
use the [class.invalid-input]
[class.invalid-input]="firstName.invalid && (firstName.dirty || firstName.touched)"
Upvotes: 1
Reputation: 1067
Please try as following:
[ngClass]="{'invalid-input': firstName.invalid && (firstName.dirty || firstName.touched)}"
Upvotes: 1