I have implemented model driven form in this demo. If the user doesn't enter anything and submits the form I am showing an error message using this logic
<div *ngIf="(!myForm.find('sku').valid && submitted)">**sku is required</div>
I am passing a boolean variable 'submitted' to check whether a control is valid or not when submitted. Is there any way to check the state of the control without passing a variable manually? Angular2 forms gives us 6 classes like ng-touched
, ng-untouched
, ng-valid
, ng-invalid
, ng-pristine
, and ng-dirty
. I want to show the error message using only these classes.
In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.
I know that question is posted a long time ago, but I got the same problem and I wanted to utilize angular control states, so found this working properly:
First I would show error only if control is not pristine:
<span class="help-block"
*ngIf="request.get('control').hasError('required') &&
!request.get('control').pristine">
This field is required!
</span>
Then you can go trough all controls and mark them as dirty in onSubmit function:
onSubmit() {
//validations
this.form.updateValueAndValidity();
if (this.form.invalid) {
Object.keys(this.form.controls).forEach(key => {
this.form.get(key).markAsDirty();
});
return;
}
//call function for saving data
this.save(this.form.value);
}
Hope this helps
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