【发布时间】:2017-12-07 10:57:39
【问题描述】:
我在表单对象parentForm 中有一个名称为'question1' 的表单控件,我已通过以下方式订阅它。
它是一个单选按钮,有两个选项 Yes 和 No,当我选择 No 时,我得到 Yes,当我选择 Yes 时,它是 No。
this.parentForm.controls['question1'].valueChanges.subscribe(
(selectedValue) => {
// If option `No is selected`
console.log(selectedValue); // displays No. OK
console.log(this.parentForm.value['question1']); // displays Yes. Problem is here
}
);
selectedValue 变量具有正确的值,但如果我这样做 console.log(this.parentForm.value['question1'] 它会给出以前的值。
在从this.parentForm.value['question1'] 检索值之前,我尝试输入setTimeout(),它工作正常。
setTimeout(() => {
console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);
但我的问题是为什么 parentForm 在其控件的值更改时不会更新,而且我也仅在值更改后才检索其值。
注意:我不想观察parentForm.valueChanges,不是我的要求。
【问题讨论】:
-
那么是什么阻止您使用
selectedValue? -
使用
this.parentForm.value['question1']我可以在组件内的任何位置访问它。selectedValue仅具有本地范围。
标签: angular angular2-forms angular2-formbuilder