Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent formControl from triggering event?

I have 3 fields linked with forms which type is number, when I modify field A, it modifies field B and C, when I modify field B it modifies field A and C and when I modify field C it modifies field A and B accordingly.

my component is as below :

this.form= this.formBuilder.group({
   fieldA: new FormControl(this.valueA),
   fieldB: new FormControl(this.valueB),
   fieldC: new FormControl(this.valueC),
});

onFieldAchanged() {
   //Do some calculs
   this.form.get('fieldB').setValue(x);
   this.form.get('fieldC').setValue(y);
}

onFieldBchanged() {
   //Do some calculs
   this.form.get('fieldA').setValue(x);
   this.form.get('fieldC').setValue(y);
}

onFieldCchanged() {
   //Do some calculs
   this.form.get('fieldA').setValue(x);
   this.form.get('fieldB').setValue(y);
}

and my template as below :

<input formControlName="fieldA" type="number" class="form-control" (ngModelChange)="onFieldAchanged()"/>
<input formControlName="fieldB" type="number" class="form-control" (ngModelChange)="onFieldBchanged()"/>
<input formControlName="fieldC" type="number" class="form-control" (ngModelChange)="onFieldCchanged()"/>

The problems come when you modify one of the field, it goes into a loop and makes the app crash.

I already tried to add the parameter emitEvent: false in my setValue() but it changed nothing

So my question: Is there a way to prevent the triggering of the other functions ? When I modify fieldA I just want to enter in my onFieldAchanged() function and set the two others values, no more.

Thank you for your help

like image 746
FairPluto Avatar asked Jan 30 '26 03:01

FairPluto


1 Answers

there sure is:

first, instead of using (ngModelChange), use valueChanges observable:

this.form.get('fieldA').valueChanges.subscribe(v => this.onFieldAchanged());
this.form.get('fieldB').valueChanges.subscribe(v => this.onFieldBchanged());
this.form.get('fieldC').valueChanges.subscribe(v => this.onFieldCchanged());

then, add the emitEvent option into your setValue fuctions to stop their valueChanges from emitting:

onFieldAchanged() {
   //Do some calculs
   this.form.get('fieldB').setValue(x, {emitEvent: false});
   this.form.get('fieldC').setValue(y, {emitEvent: false});
}

the issue is mixing ngModel with reactive forms. gotta choose one.

like image 94
bryan60 Avatar answered Feb 01 '26 17:02

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!