这快把我逼疯了,我压力很大,不能在这上面再耗上一整天。
我试图在组件内手动设置一个控制值('dept'),它只是不工作-甚至新值日志控制台正确。
下面是FormBuilder实例:
initForm() {
this.form = this.fb.group({
'name': ['', Validators.required],
'dept': ['', Validators.required],
'description': ['', Validators.required],
});
}
这是接收所选部门的事件处理程序:
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;
}
表单提交后,我登出这个。表格栏还是空白!我见过其他人使用updateValue(),但这是测试版。1,我不认为这是一个有效的方法来调用控件。
我还尝试调用updateValueAndValidity(),但没有成功:(。
我只会在表单元素上使用ngControl="dept",就像我对表单的其余部分所做的一样,但它是一个自定义指令/组件。
<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>
可以使用以下方法更新响应式表单控件的值。以下任何一种方法都适合您的需要。
使用setValue()的方法
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
使用patchValue()的方法
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
最后一个方法将循环遍历表单中的所有控件,因此在更新单个控件时不建议使用该方法
您可以在事件处理程序中使用任何方法
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
控件可在必要时更新表单组中的多个控件
this.form.patchValue({"dept": selected.id, "description":"description value"});
可以使用以下方法更新响应式表单控件的值。以下任何一种方法都适合您的需要。
使用setValue()的方法
this.form.get("dept").setValue(selected.id);
this.form.controls["dept"].setValue(selected.id);
使用patchValue()的方法
this.form.get("dept").patchValue(selected.id);
this.form.controls['dept'].patchValue(selected.id);
this.form.patchValue({"dept": selected.id});
最后一个方法将循环遍历表单中的所有控件,因此在更新单个控件时不建议使用该方法
您可以在事件处理程序中使用任何方法
deptSelected(selected: { id: string; text: string }) {
// any of the above method can be added here
}
控件可在必要时更新表单组中的多个控件
this.form.patchValue({"dept": selected.id, "description":"description value"});