Angular 2 个禁用的控件未包含在 form.value

Angular 2 disabled controls do not get included in the form.value

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

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,如果所有控件都已启用,则输出将是:

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

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

{"Enabled":true} 

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

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

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

欢迎提出您的想法。

您可以使用:

this.notelinkingForm.getRawValue()

来自Angular docs

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.

我使用的另一个选项是:

this.form.controls['LinkToPreceeding'].value;

谢谢 @Sasxa 为我提供了我需要的 80%。

对于那些正在寻找相同问题的解决方案但对于嵌套表单我能够通过更改我通常的方法来解决的人

this.notelinkingForm.get('nestedForm').value

this.notelinkingForm.getRawValue().nestedForm

如果您使用 readonly 而不是 disabled,它仍然不可编辑,但数据将包含在表单中。但这并非在所有情况下都是可能的。例如。它不适用于单选按钮和复选框。参见 MDN web docs。在这些情况下,您必须申请此处提供的其他解决方案。

我们有两种方法可以获取禁用的表单值。 第一

 onSubmit(){
 for (const prop in this.formControl.controls) {
      this.formControl.value[prop] = this.formControl.controls[prop].value;
    }
}

第二种方式 您可以在 onSubmit 事件中启用表单

 onSubmit(){
     this.formControl.enable() 
   //Your logical/operational statement goes here

  //at last if you wish you can again disable your form like this
   this.formControl.disable();
}