我在一个名为'question1'
的表单控件内,该控件位于parentForm
表单对象中,我以以下方式订阅它。
它是一个具有两个选项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
? - Harry Ninhthis.parentForm.value['question1']
可以在组件的任何位置访问它。selectedValue
仅具有局部作用域。 - Amit Chigadani