4

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.

enter image description here

Is there a way to determine if the form is submitted so that I can display my inline validation errors?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Shame. Glad to see it's coming though!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.