Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop infinite loop reactive forms control update in Angular

I have 2 inputs on a form, a numeric input called "ageMonths", and a date selector called "dateOfBirth".

I want the user to be able to enter either months for an age, or use the date selector to pick a Date of Birth (dob). If they enter a dob from the date selector, I want the month field to update to the age in months. If they enter an age in months, I want the date selector to jump to that date. I'm using reactive forms.

I added a class level variable to hold a toggle which is read and set each time a value changes for either control. But this isn't working as expected, I assume due to events not firing in the order I am expecting them to.

What do I need to do to make this work?

My code is:

ignoreDateUpdate = false;
form: FormGroup;
...
constructor(...){
this.form = new FormGroup({
    dateOfBirth: new FormControl({ value: new Date()}),
    ageMonths: new FormControl({ value: 0 }),
    ...
});
...
this.form.get('ageMonths').valueChanges.subscribe(
m => {
    if (ignoreDateUpdates) {return};
    ignoreDateUpdates = true;
    <code to set DateSelectorValue>
    ignoreDateUpdates = false;
    });
this.form.get('dateOfBirth').valueChanges.subscribe(
dob => {
    if (ignoreDateUpdates) {return};
    ignoreDateUpdates = true;
    <code to set MonthsInput>
    ignoreDateUpdates = false;
});
}
like image 926
Molloch Avatar asked Oct 19 '25 15:10

Molloch


2 Answers

I'm answering this as I've got the required behaviour by adding the {emitEvent: false} option to my setValue calls:

const calcDate = <calculate date from months value>;
this.form.get('dateOfBirth').setValue(calcDate, { emitEvent: false });

But I'd still like to know why the toggle field didn't work as expected if anyone can explain?

like image 197
Molloch Avatar answered Oct 22 '25 06:10

Molloch


i also implemented this kind of functionality in my app,i have two input box one is hour and second is minutes whenever user enter value in hours then i convert hour into minutes and update minutes input box,when user enter minutes in minutes input box then i convert minutes into hours and update hour input box.

private  ignoreDateUpdates=true;        
this.form.get('ageMonths').valueChanges.subscribe(m => {
        if (ignoreDateUpdates) {
        ignoreDateUpdates = false;
        <code to set DateSelectorValue>
         }
        else{
      ignoreDateUpdates = true;
         }       
 });
    this.form.get('dateOfBirth').valueChanges.subscribe(
    dob => {
        if (ignoreDateUpdates) {
        ignoreDateUpdates = false;
        <code to set MonthsInput>
       }
        else{
        ignoreDateUpdates = true;
      }    
});
    }
like image 36
Shahid Islam Avatar answered Oct 22 '25 08:10

Shahid Islam



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!