Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - How to set `touched` property on form to true

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

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 every input to true?

like image 207
georgej Avatar asked Feb 22 '17 18:02

georgej


People also ask

When the user blurs the form control element the control is marked as touched?

True if the control is marked as touched . A control is marked touched once the user has triggered a blur event on it. A control is untouched if the user has not yet triggered a blur event on it. A multicasting observable that emits an event every time the value of the control changes, in the UI or programmatically.

How do you make angular forms dirty?

You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.


1 Answers

There's a pretty straightforward method to do this: markAsTouched. It should be enough to use it on the form group.

this.addressForm.markAsTouched() 

In case you want for some reason to mark all controls manually, they itself have this method available.

markAsTouched is a method of the AbstractControl all form elements inherit 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 the form objects. Or just visit the documentation.

like image 144
Mateusz Kocz Avatar answered Sep 19 '22 04:09

Mateusz Kocz