发送带有原始数据的 Angular2 表单

Send Angular2 form with pristine data

问题:我想提交一个包含原始数据的表单,但验证器不允许我这样做,因为表单无效。

我正在尝试使用数据驱动方法发送表单,使用表单生成器,我要发送的数据在模态中。模态的目的是用户可以编辑一些数据,模态上的输入字段填充了以前的数据,这就是为什么我不需要检查用户是否更改了值,但是我仍然需要检查如果字段不为空。

忽略模态框底部的选择器。

[模态截图][1] [1]: https://i.stack.imgur.com/Q1GU4.png

表单生成器代码

this.editProblemForm = this._formBuilder.group({
  'problemDetails': this._formBuilder.group({
    'engDescription': ['', Validators.required],
    'spnDescription': ['', Validators.required]
  })
});

模态代码,其中检索值,片段底部是一个按钮,当表单无效时该按钮被禁用,问题是当用户打开模态时所有信息已经填满,所以按钮不应该被禁用,但它确实被禁用了。

<!-- Descriptions -->
<div class="row margin-top20">
  <div class="input-group margin-top20">
    <label for="desc_engEdit">Problem description: English</label>
    <textarea id="desc_engEdit" rows="6" formControlName="engDescription" [value]="descriptionEng"
              class="form-control white-space"></textarea>
  </div>
</div>
<div class="row margin-top20 margin-bottom20">
  <div class="input-group margin-top20">
    <label for="desc_spnEdit">Problem description: Spanish</label>
    <textarea id="desc_spnEdit" rows="6" formControlName="spnDescription" [value]="descriptionSpn"
              class="form-control white-space"></textarea>
  </div>
</div>

<button [disabled]="!editProblemForm.valid" type="submit" class="btn btn-primary">Save changes
                  </button>

使用@silentsod 方法的解决方案

updateFormValues(){

let formObject : any;
  formObject  = this.editProblemForm.controls['problemDetails'];
  formObject.controls['engDescription'].setValue(this.descriptionEng);
  formObject.controls['spnDescription'].setValue(this.descriptionSpn);
}

谢谢!!

问题在于,对于 Reactive Forms(模型驱动),您需要调用 setValue 才能正确更新控件值。否则,它会认为表单是空的并且没有满足您要求的验证器。

假设您可以控制发送到模式中的内容,那么在打开时,在您的 模式组件 TypeScript:

onOpen() { //or however you've named it/arguments you have
   this.editProblemForm.controls['problemDetails'].controls['engDescription'].setValue(descriptionEng); //wherever you got that from
   this.editProblemForm.controls['problemDetails'].controls['spnDescription'].setValue(descriptionSpn); //wherever you got that from
}

顺便说一句,您也不应该使用 [disabled],而是在控件上以编程方式调用 .disable().enable()。在您的控制台日志中会有一条关于它的警告消息。