表单控件的valueChanges给出先前的值 [英] Form control valueChanges gives the previous value

查看:765
本文介绍了表单控件的valueChanges给出先前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单对象 parentForm 中有一个名称为'question1'的表单控件,并且已经订阅了它

I have a form control with name 'question1' within the form object parentForm and I have subscribed to it in the following way.

它是一个单选按钮,带有两个选项,当我选择时,我会得到,而当我选择

Its a radio button with two options Yes and No, when I select No I get Yes and when I select Yes its a 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'] 它给出了先前的值。

selectedValue variable has the correct value but if I do console.log(this.parentForm.value['question1'] it gives the previous value.

我试图从 this.parentForm.value ['question1'] 检索值之前放入 setTimeout(),它

I tried to put a setTimeout() before retrieving value from this.parentForm.value['question1'], It just works fine.

setTimeout(() => {
  console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);

但是我的问题是为什么 parentForm 控件的值更改时为什么不更新,我也只在值更改后才获取它的值。

But my question is why parentForm is not updated when its control's value changes and that too I am retrieving its value only after value was changed.

注意:我不想观察 parentForm.valueChanges ,而不是我的要求。

Note: I don't want to observe for parentForm.valueChanges, not my requirement.

推荐答案

valueChanges 是可观察的,因此您可以将 pairwise 用管道传输以获取订阅中的上一个和下一个值。

valueChanges is an Observable so you can pipe pairwise to get the previous and next values in the subscription.

// No initial value. Will emit only after second character entered
this.form.get('fieldName')
  .valueChanges
  .pipe(pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );



// Fill buffer with initial value, and it will emit immediately on value change
this.form.get('fieldName')
  .valueChanges
  .pipe(startWith(null), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

在StackBlitz中工作的示例:
https://stackblitz.com/edit/angular-reactive-forms-vhtxua

Example of it working in StackBlitz: https://stackblitz.com/edit/angular-reactive-forms-vhtxua

这篇关于表单控件的valueChanges给出先前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆