Angular 2 禁用控件未包含在 form.value 中 [英] Angular 2 disabled controls do not get included in the form.value

查看:23
本文介绍了Angular 2 禁用控件未包含在 form.value 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我在 Angular 2 反应式表单上禁用控件,则该控件不会包含在 form.value 中.例如,如果我像下面这样定义表单:

I have noticed that if I disable a control on an Angular 2 reactive form then the control does not get included in the form.value. For example, if I define my form like below:

this.notelinkingForm = new FormGroup({
    Enabled: new FormControl(settings.Enabled, Validators.required),
    LinkToPreceeding: new FormControl({value: settings.LinkToPreceeding, disabled: !settings.Enabled}, Validators.required),
    LinkingTolerance: new FormControl({value: settings.LinkingTolerance, disabled: !settings.Enabled}, Validators.required)
});

并检查this.notelinkingForm.value,如果启用了所有控件,则输出将是:

and check the this.notelinkingForm.value, if all the controls are enabled then output would be:

{"Enabled":true, "LinkToPreceeding": true, LinkingTolerance:"100"} 

但是,当某些控件被禁用时:

However, when some of the controls are disabled it would be:

{"Enabled":true} 

注意如何排除禁用的控件.

Notice how the disabled controls are excluded.

我的意图是,当表单更改时,我希望能够将 form.value 及其中的所有属性传递给我的其余 API.如果它不包含禁用项,这显然是不可能的.

My intent is that when the form changes I want to be able to pass the form.value with all the properties in it off to my rest API. This won't be possible obviously if it does not contain the disabled items.

我在这里遗漏了什么还是这是预期的行为?有没有办法告诉 Angular 在 form.value 中包含禁用的项目?

Am I missing something here or is this the expected behavior? Is there a way to tell Angular to include the disabled items in the form.value?

欢迎你的想法.

推荐答案

您可以使用:

this.notelinkingForm.getRawValue()

来自 Angular 文档:

如果您想包括所有值而不管禁用状态如何,请使用此方法.否则,value 属性是获取组值的最佳方式.

If you'd like to include all values regardless of disabled status, use this method. Otherwise, the value property is the best way to get the value of the group.

这篇关于Angular 2 禁用控件未包含在 form.value 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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