Reputation: 10838
I am using FormBuilder
and have simple validation which checking if field is valid with *ngIf="!field.valid
<input [ngFormControl]="myForm.controls['field']"
type="text" id="field" #field="ngForm">
<span class="error" *ngIf="!field.valid">Error</span>
Always when components are loaded the errors
are shown before I even type anything in any inputs. How to stop Angular 2 of running validation on component load so it fires only when typing?
Upvotes: 1
Views: 2026
Reputation: 86790
Basically there are three types of error class for inputs of form,
dirty - when Control's value has changed
touched - when Control has been visited
valid - when Control's value is valid(as per validation provided)
so as per your requirements you need to use dirty or touched
class from among classes,
you can use [hidden] as well as *ngIf
to use this error class (to show error message).
you could use like this:
<span [hidden]="name.valid" *ngIf='name.touched'><b>Required</b></span>
see working example for form using error classes.
for more info related to error classes see here
Upvotes: 2
Reputation: 658017
Include a check if the field is touched
or dirty
<span class="error" *ngIf="!field.valid && field.dirty">Error</span>
Upvotes: 1