I have an input
field. The field should not be empty. If it is, I want Bootstrap's is-invalid
class to be assigned to it. The problem I am facing is that if I just click on the field, do not type anything and then leave the field, the field doesn't turn red (has-error
doesn't get assigned to the field). However if I type something and delete it completely and then leave the field, the field turns red.
The HTML
is
<input id="firstname" type="text" class="form-control" formControlName="firstName" [ngClass]="validateField('firstName')" (blur)="setFieldStatus('firstName')" required>
.ts
is
validateField(field:string){
console.log("validating field: " +field)
return this.helper.displayFieldCss(this.signupForm,field);
}
/*mark a control field as touched on losing focus from that field.*/
setFieldStatus(field:string){
console.log("inside setFieldStatus for field "+field)
const control = this.signupForm.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
}
};
helper.ts
displayFieldCss(form: FormGroup, field: string) {
console.log("in displayFieldCss for field "+field);
if(!form.get(field).pristine) { //check for validity only if the user has interacted with the field. Without this check, the default field will have red border.
let fieldValid: boolean = form.get(field).valid;
return {
'is-invalid': !fieldValid, // if fieldvalid returns false i.e. field is not valid then we want has-error css. So set it to true (opp. of fieldValid)
'is-valid': fieldValid //if fieldvalid returns true i.e. field is valid then we want has-success css. So set it to true (value of fieldValid)
//'has-feedback': this.isFieldValid(field)
}
} else {//if field is pristine (not touched by user at all) then dont display error or success
return {
'is-invalid': false, // if field is pristine (not touched by user at all) then dont display error or success
'is-valid': false//if field is pristine (not touched by user at all) then dont display error or success
}
}
}
My logic is, in template, ngClass
gets is-valid
or is-invalid
depending on whether user has interacted with the field or not. I do not want the field to be red when the form loads up (pristine check handles that)
when the user leaves the field, I mark the field touched
. Now, I can see the issue that [ngClass]
gets assigned when the field is created but it doesn't get updated when (blur)
is called. I need to update [ngClass]
when (blur)
is triggered but don't know how to. blur
is handled in component's class while [ngClass]
is in HTML.