anonymous
anonymous

Reputation: 1681

Listening to form value changes called frequently

I have three from controls,

The custom formcontrol is a simple counter that increments or decrement a value in an inputbox. I listen to value changes of the whole form .The problem is when i include this the custom form control, The form value changes triggered on some scenario's like when other input tag's get focus or on click of the body of the document or on page scroll. I know the value change is only subscribed to value changes of any of the formcontrols in the form but it also triggers on weird cases as mentioned above.

Here is what i have tried,

ngOnInit(){
    this.profileForm.valueChanges.subscribe( x => {
      console.log('value changing');
    })
}

Here is the code on stackblitz

Here are the steps to reproduce the issue, click on the firstname and then click on lastname and you will see the console log messages.

Upvotes: 0

Views: 2468

Answers (3)

L. Kvri
L. Kvri

Reputation: 1703

Maybe you can use updateOn: 'blur' when you create a reactive form with FormBuilder. About updateOn. You can use it on a field(FormControl) and a form(FormGroup).

Upvotes: 0

dAxx_
dAxx_

Reputation: 2290

So, this was very odd behavior to me, so I immediately checked your custom formControl, and I find out that you calling

  ngAfterContentChecked() {
    this.propagateChange(this.counterValue);
  }

ngAfterContentChecked - Respond after Angular checks the content projected into the directive/component. Called after the ngAfterContentInit() and every subsequent ngDoCheck().

So, the problem here is that this hook calling after ngDoCheck

ngDoCheck() Detect and act upon changes that Angular can't or won't detect on its own.

Called during every change detection run, immediately after ngOnChanges() and ngOnInit().

So basically, every change detection run this form control emits the event.
You should delete this from the custom control, and you will remain the same basic behavior without the endless loop that calling your emits.

Upvotes: 1

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

You can do some hacking to check form input values are not same. Here is the updated stackblitz. https://stackblitz.com/edit/angular-7bxnw1

Upvotes: 0

Related Questions