【发布时间】:2017-07-12 23:21:04
【问题描述】:
我的组件中有一个响应式表单,我想将每个输入上的touched 属性设置为等于true。我当前的代码会这样做,但会引发错误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?
【问题讨论】:
-
Touched 和 Untouched 是只读属性。不能赋值。
-
顺便说一句,如果您在 HTML 表单元素上使用 #myForm="ngForm" ,您可以在 HTML 中访问 myForm.submitted,因此可能不需要打扰 .touched
-
@RonNewcomb 您应该将此添加为答案。它为我节省了一些精力
-
this.addressForm.controls[key].markAsTouched()
-
form.control.markAllAsTouched()
标签: forms angular angular2-forms reactive-forms