Reactive Forms - mark fields as touched

后端 未结 19 1515
旧时难觅i
旧时难觅i 2020-12-04 23:15

I am having trouble finding out how to mark all form\'s fields as touched. The main problem is that if I do not touch fields and try to submit form - validation error in not

19条回答
  •  攒了一身酷
    2020-12-04 23:45

    Here is how I do it. I don't want the error fields to show until after the submit button is pressed (or the form is touched).

    import {FormBuilder, FormGroup, Validators} from "@angular/forms";
    
    import {OnInit} from "@angular/core";
    
    export class MyFormComponent implements OnInit {
      doValidation = false;
      form: FormGroup;
    
    
      constructor(fb: FormBuilder) {
        this.form = fb.group({
          title: ["", Validators.required]
        });
    
      }
    
      ngOnInit() {
    
      }
      clickSubmitForm() {
        this.doValidation = true;
        if (this.form.valid) {
          console.log(this.form.value);
        };
      }
    }

    title is required

提交回复
热议问题