Angular2 - 如何设置“已触摸”属性为true [英] Angular2 - How to set `touched` property on from to true

查看:143
本文介绍了Angular2 - 如何设置“已触摸”属性为true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的组件中有一个反应形式,我想在每个输入中设置触及的属性,等于 true 。我目前的代码是这样的,但它会抛出错误无法设置属性触及#< AbstractControl>它只有一个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 is this but it throws me 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;
}

如何设置触及每个输入的值为 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 - 如何设置“已触摸”属性为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆