Angular 2 display validation errors after form submission

I am creating a model-driven Angular2 model. Most of the examples I found will disable the submit button until the form is valid. However, I am not a fan of this template and prefer to display any potential errors for the user after submitting the form.

I compared the data of my ControlGroup form before and after submitting and I see no difference.

enter image description here

Is there a way to determine if the form has been submitted so that I can display my built-in validation errors?

+4
source share
2 answers

There is currently no way. You can set the flag in the submit handler yourself.

Work continues though


- https://github.com/angular/angular/issues/2960 - https://github.com/angular/angular/pull/7449

+3

, - Angular .

. , - (, , , submit, , , ).

:

  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);           
      }
    });
  }

.

0

All Articles