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

问题描述



我试图手动设置一个控制值('dept')在组件中,并且它只是不工作 - 即使是新的值日志也能正确控制。



这里是FormBuilder实例: p>

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

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

  deptSelected(选中:{id:string; text:string}){
console.log(选中)//显示正确选择!

//这是我如何设置值
this.form.controls ['dept']。value = selected.id;
}

现在当表单被提交时,我注销 this.form 该字段仍然是空白的!我见过其他的ppl使用 updateValue(),但这是beta.1,我没有看到它作为调用控件的有效方法。



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



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

 < ng-select 
[data] =dept
[multiple] =false
[items] =depts
(selected)=deptSelected($ event)<! - 这就是价值到达我的方式 - >
[placeholder ] ='没有部门选择'>< / ng-select>


解决方案

更新日期:19/03/2017

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

旧:



现在我们被迫做了一次类型转换:

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

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


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

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

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

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.

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

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>
解决方案

Updated: 19/03/2017

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

OLD:

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