本文介绍了手动设置 FormBuilder 控件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我发疯了,我受不了了,不能再花一整天的时间.

This is driving me nuts, I'm under the gun and can't afford to spend another whole day on this.

我正在尝试在组件中手动设置一个控制值(dept"),但它不起作用 - 即使是新值也能正确记录到控制台.

I am trying to manually set a control value ('dept') within the component, and it's just not working - even the new value logs to console properly.

这是 FormBuilder 实例:

Here is the FormBuilder Instance:

initForm() {
  this.form = this.fb.group({
    'name': ['', Validators.required],
    'dept': ['', Validators.required],
    'description': ['', Validators.required],
  });
}

这是接收所选部门的事件处理程序:

This is the event handler that receives the selected dept:

deptSelected(selected: { id: string; text: string }) {
  console.log(selected) // Shows proper selection!

  // This is how I am trying to set the value
  this.form.controls['dept'].value = selected.id;
}

现在当表单提交并且我注销this.form时,该字段仍然是空白的!我见过其他人使用 updateValue() 但这是 beta.1,我不认为这是调用控件的有效方法.

Now when the form is submitted and I log out this.form the field is still blank! I've seen other ppl use updateValue() but this is beta.1 and I don't see that as a valid method to call on the control.

我也尝试调用 updateValueAndValidity() 没有成功:(.

I have also tried to call updateValueAndValidity() with no success :(.

我只会在表单元素上使用 ngControl="dept",就像我对表单的其余部分所做的一样,但它是一个自定义指令/组件.

I would just use ngControl="dept" on the form element, like I'm doing with the rest of the form but its a custom directive/component.

<ng-select
  [data]="dept"
  [multiple]="false"
  [items]="depts"
  (selected)="deptSelected($event)" <!-- This is how the value gets to me -->
  [placeholder]="'No Dept Selected'"></ng-select>

推荐答案

更新:19/03/2017

this.form.controls['dept'].setValue(selected.id);

旧:

现在我们被迫进行类型转换:

For now we are forced to do a type cast:

(<Control>this.form.controls['dept']).updateValue(selected.id)

不是很优雅,我同意.希望这在未来的版本中得到改进.

Not very elegant I agree. Hope this gets improved in future versions.

这篇关于手动设置 FormBuilder 控件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:27