表单控件valueChanges给出以前的值

时间:2017-07-04 06:02:19

标签: angular angular2-forms angular2-formbuilder

我在表单对象'question1'中有一个名为parentForm的表单控件,我已按以下方式订阅它。

它是一个带有两个选项YesNo的单选按钮,当我选择No时,我会Yes当我选择Yes时,No 1}}。

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'],则会给出之前的值。

我在从setTimeout()检索值之前尝试放置this.parentForm.value['question1'],它运行正常。

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

但我的问题是为什么parentForm在其控件的值发生变化时不会更新,而且我也只是在更改值后才检索它的值。

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

4 个答案:

答案 0 :(得分:25)

{/ 1}}事件在新值更新为valueChanges后触发 之前将更改冒泡到其中父母和祖先。因此,您必须访问FormControl本身(刚被修补)的值,而不是FormControl值对象的字段(在事件期间未触及)。

鉴于此,请改用FormGroup

this.parentForm.get('question1').value

答案 1 :(得分:18)

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

// 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

答案 2 :(得分:4)

还有一个选项,但它可能并不适用于所有情况:您可以在FormControl中更新selectedValue之前等待 one tick

setTimeout( () => console.log( selectedValue ) );

有关同步/异步表单主题的更多内容:Angular Guide文档中的Reactive forms

答案 3 :(得分:1)

尝试这样做

this.parentForm.controls['question1'].valueChanges.subscribe(
    (selectedValue) => {
      console.log(selectedValue);
      console.log(this.parentForm.value.question1);     
    }
);

如果更新了FormBuilder的控件,您可以通过属性值立即从FormBuilder对象中恢复最后一个值