Sammaye
Sammaye

Reputation: 43884

How to use FormControl.valueChanges to format input value

I want to format every value entered into a certain FormControl on my page using parseFloat, due to a requirement from a third party plugin, so I made something like:

this.form.get('latitude').valueChanges.subscribe(e => {
  this.form.patchValue({latitude: parseFloat(e)});
});

Obviously this doesn't work, it creates an infinite loop.

How can I do something like this but without the loop?

Upvotes: 0

Views: 493

Answers (1)

Morphyish
Morphyish

Reputation: 4072

patchValue accept an secondary argument containing options, including an emitEvent option.

You can update your code with

this.form.get('latitude').valueChanges.subscribe(e => {
  this.form.patchValue({latitude: parseFloat(e)}, {emitEvent: false});
});

and you will avoid the infinite loop as the patchValue method won't trigger another valueChanges.

Upvotes: 1

Related Questions