Skip to content

[docs] Reactive form gatcha #49898

@yelhouti

Description

@yelhouti

Describe the problem that you experienced

I am often writing complexe reactive forms.
And sometimes on valuechanges of one of the fields I need to recompute some value to show in my gui.
And it often felt random that, sometime, one the callback of the value changes, I get the old value, and other times the new value. Today I decided to better understand this and document it somewhere for others.

After reading and playing with the code I think I finally get it.

If you try to access the value of a control through its parent, you always get the old value, since it isn't updated yet.

here is a common use case.
on change of field1 or field2 you want to automatically change field 3.

    this.editForm.controls.items.valueChanges.pipe(takeUntil(this.onDestroySubject)).subscribe(items => {
      this.updateTotals();
    });

    this.editForm.controls.discount.valueChanges.pipe(takeUntil(this.onDestroySubject)).subscribe(discount => {
      this.updateTotals();
    });
    
  protected updateTotals(): void {
    const items = this.editForm.value.items;
    const discount = this.editForm.value.discount ?? 0;
    const total = items.map(si => si.price).reduce((x, y) => x + y, 0) * (1 - discount);
    this.editForm.patchValue({
      total,
    });
  }

This doesn't work, since the parent isn't yet updated when the call back is called. instead you should write you code like this:

  protected updateTotals(): void {
    const items = this.editForm.controls.items.value;
    const discount = this.editForm.controls.discount.value ?? 0;
    const total = items.map(si => si.price).reduce((x, y) => x + y, 0) * (1 - discount);
    this.editForm.patchValue({
      total,
    });
  }

Enter the URL of the topic with the problem

https://angular.io/guide/reactive-forms

Describe what you were looking for in the documentation

I don't know where exactly stuff like this should be on the docs, or maybe there is another place to write this kind of stuff.

Describe the actions that led you to experience the problem

No response

Describe what you want to experience that would fix the problem

No response

Add a screenshot if that helps illustrate the problem

No response

If this problem caused an exception or error, please paste it here

No response

If the problem is browser-specific, please specify the device, OS, browser, and version

No response

Provide any additional information here in as much as detail as you can

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions