Angular2 - How to set the "touch" property of a form to true

I have a reactive form in my component, and I want to set the touched property for each of the inputs to true . My current code does this, but throws a Cannot set property touched of #<AbstractControl> which has only a getter error:

 addressForm: FormGroup; ... this.addressForm = this._fb.group({ street: ["", [<any>Validators.required]], city: ["", [<any>Validators.required]], state: ["", [<any>Validators.required]], zipCode: ["", [<any>Validators.required]], country: ["", [<any>Validators.required]] }); ... for (var key in this.addressForm.controls) { this.addressForm.controls[key].touched = true; } 

How can I set the touched value of each contribution to true ?

+16
source share
2 answers

There is a fairly simple way to do this: markAsTouched . It is enough to use it in a group of forms.

 this.addressForm.markAsTouched() 

If for any reason you want to flag all controls manually, they themselves have this method.

markAsTouched is a method of AbstractControl form elements inherited from. Out of curiosity, you might want to visit the @angular/forms/src/model.d.ts declaration file to find some more interesting methods of form objects. Or just visit the documentation .

+47
source

If you use #myForm="ngForm" in your HTML form element, you have access to myForm.submitted in HTML, so you don't need to worry about .touched

0
source

Source: https://habr.com/ru/post/1264593/


All Articles