【问题标题】:Send Angular2 form with pristine data发送带有原始数据的 Angular2 表单
【发布时间】:2017-04-10 20:07:13
【问题描述】:

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

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

忽略模式底部的选择器。

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

表单生成器代码

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

模态代码,取值的地方,在sn-p的底部是一个按钮,当表单无效时被禁用,问题是当用户打开模态时,所有的信息都已经填充,所以按钮不应该被禁用,但它是。

<!-- 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);
}

谢谢!!

【问题讨论】:

  • 你能说明你是如何设置这些值的吗?
  • @silentsod 我刚刚更新了问题,谢谢

标签: forms angular angular2-forms


【解决方案1】:

问题在于,对于反应式表单(模型驱动),您需要调用 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()。您的控制台日志中会显示一条警告消息。

【讨论】:

  • 成功了!!!我只需要先将表单对象保存在一个变量中,因为 TypeScript 不允许我在一行中完成所有操作。谢谢!
猜你喜欢
  • 2017-08-08
  • 1970-01-01
  • 2018-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
相关资源
最近更新 更多