RangeError: Maximum call stack size exceeded when using valueChanges.subscribe

My answer is just development of this one.

By adding distinctUntilChanged() in the pipeline just before subscribe() you avoid the "Maximum call stack size exceeded" because

distinctUntilChanged method only emit when the current value is different than the last.

The usage:

this.userForm.get('password')
  .valueChanges.pipe(distinctUntilChanged())         
  .subscribe(val => {})

Documentation


If you want to subscribe to any form changes and still run patchValue inside it, then you could add the {emitEvent: false} option to patchValue, thus the patching will not trigger another change detection

code:

this.formGroup
    .valueChanges
    .subscribe( _ => {
        this.formGroup.get( 'controlName' ).patchValue( _val, {emitEvent: false} );
    } );

PS. This is also less tedious than subscribing to each form control one-by-one to avoid triggering change max call stack exceeded. Especially if you form has 100 controls to subscribe to.

Now to elaborate further, if you still need to updateValueAndValidity inside the subscription, then I suggest you use the distinctUntilChanged rxjs operator, to only run the subscription, when some value changes.

distinctUntilChanged documentation can be found here

https://www.learnrxjs.io/operators/filtering/distinctuntilchanged.html

distinctUntilChanged - Only emit when the current value is different than the last.

Now we will also have to make it a custom validation function, because by default, distinctUntilChanged validates objects by pointer and the pointer is new on every change.

this.formGroup
    .valueChanges
    .distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b))
    .subscribe( _ => {
        this.formGroup.get( 'controlName' ).patchValue( _val, {emitEvent: false} );
        this.formGroup.get( 'controlName' ).updateValueAndValidity();
    } );

And voila, we are patching and updating, without running into the maximum call stack!