Changes form control value gives previous value

I have a control form with a name 'question1'inside the form object parentForm, and I subscribed to it as follows.

Its a switch with two parameters Yesand Nowhen I select No, I receive Yesand when I select Yesit 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
  }
);

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

I tried putting setTimeout()before getting the value out this.parentForm.value['question1'], it just works fine.

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

But my question is why parentFormit is not updated when its control value changes, and that I also return its value only after the value has been changed.

. parentForm.valueChanges, .

+12
4

valueChanges , FormControl, . FormControl ( ), FormGroup ( ).

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

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

, : selectedValue FormControl:

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

sync/async:

+3

valueChanges Observable, 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

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

FormBuilder , FormBuilder

+1

Source: https://habr.com/ru/post/1680686/


All Articles