Reputation: 1363
I'm building a model-driven Angular2 form. Most examples I have found will disable the submit button until the form is valid. However, I'm not a fan of this pattern and would rather display any potential errors to the user after the form has been submitted.
I've compared my form ControlGroup data before & after submission and cannot see any difference.
Is there a way to determine if the form is submitted so that I can display my inline validation errors?
Upvotes: 4
Views: 3358
Reputation: 5552
I don't think the accepted answer - and the related update to Angular really answers this question.
You can use the form.submitted? flag to find out if the user already tried to submit - but that will not automatically display errors (eg. if you have required fields and the user does not enter anything at all on your form but just clicks submit, then you would expect all required fields to show the required error notice).
This can be done as follows:
onSubmit() {
if (this.form.valid) {
console.log('form submitted');
} else {
this.validateAllFormFields(this.form);
};
}
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
Credit and full explanation here.
Upvotes: 1
Reputation: 657078
There is currently no way. You can set a flag in the submit handler yourself.
It is work in progress though
See
- https://github.com/angular/angular/issues/2960
- https://github.com/angular/angular/pull/7449
Upvotes: 3