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

谁说胖子不能爱 提交于 2019-12-05 09:55:09

问题


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?


回答1:


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.




回答2:


If you use #myForm="ngForm" on your HTML form element, you have access to myForm.submitted in the HTML, so might not need to bother with .touched



来源:https://stackoverflow.com/questions/42399462/angular2-how-to-set-touched-property-on-form-to-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!