Home > Mobile >  Angular : ERROR RangeError: Maximum call stack size exceeded message when I type in inputs
Angular : ERROR RangeError: Maximum call stack size exceeded message when I type in inputs

Time:09-22

I'm getting ERROR RangeError: Maximum call stack size exceeded message in console when I type something in one of this inputs

app.component.html

<div class="container-wrap">
    <div class="container">
        <input type="number" [formControl]="input1">
        <input type="number" [formControl]="input2">
    </div>
</div>

app.component.ts

constructor() { }

  input1:FormControl=new FormControl();
  input2:FormControl=new FormControl();

  ngOnInit(): void {

    this.input1.valueChanges
    .pipe(tap(value=>{
      this.input2.setValue(value);
    })).subscribe();

    this.input2.valueChanges
    .pipe(tap(value=>{
      this.input1.setValue(value);
    })).subscribe();

  }

Looks like typing in one of my inputs calls endless valueChanges loop in app.

I want to make when I type in iput1 something it types in input2 and also when I type in input2 it will change input in input1.

how to fix this?

CodePudding user response:

You can use a FormGroup containing your two FormControl.

With a FormBuilder it'll look like this:

constructor(formBuilder: FormBuilder) {}

ngOnInit(): void {
  this.formGroup = this.formBuilder.group({
              inputA: this.input1,
              inputB: this.input2
  });
  this.formGroup.valueChanges.subscribe(values => [switch values here]);
}

CodePudding user response:

You can pass an extra argument to setValue which should stop your valueChanges being run on the value you are editing.

this.input1.valueChanges
    .pipe(tap(value=>{
      this.input2.setValue(value, { emitEvent: false });
    })).subscribe();
    

this.input2.valueChanges
    .pipe(tap(value=>{
      this.input1.setValue(value, { emitEvent: false });
    })).subscribe();

CodePudding user response:

The error is happening because of the infinity loop caused by your value changes subscription, once one input change, it trigger the second input value to change, then the second value change listener will trigger the first and the loop continue, you can fix this by adding emitEvent: false to your form control set value

  this.input2.setValue(value, {emitEvent: false});
  • Related