问题描述
我的组件中有一个反应形式,我想在每个输入中将touched
属性设置为等于true
.我当前的代码可以执行此操作,但是会引发错误Cannot set property touched of #<AbstractControl> which has only a getter
:
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;
}
如何将每个输入的touched
值设置为true
?
How can I set the touched
value of every input to true
?
推荐答案
有一个非常简单的方法可以做到这一点:markAsTouched
.在表单组上使用它就足够了.
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
是AbstractControl
所有表单元素所继承的方法.出于好奇,您可能想访问@angular/forms/src/model.d.ts
声明文件,以找到表单对象的一些更有趣的方法.或只需访问文档.
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.
这篇关于Angular2-如何将窗体上的`touched`属性设置为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!