How to not trigger value changes when editing a FormControl in Angular 2+

Sami C.
2 min readJan 25, 2019

Tl;dr

We had a issue where the valuechanges would go off when editing the value of a formcontrol. Wouter Van Gorp showed me a great solution for this:

emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control value is updated. When false, no events are emitted.

this.filterForm.setValue(value, {emitEvent:false});

Explaining the problem

Let’s say we would have an input field with a dropdown, when the user selects an item in the dropdown, the selected item will be displayed in the autocomplete field.

Input field with dropdown

I made a quick example to show the problem:

input = new FormControl()
constructor() {
this.input.valueChanges
// Only if the text is longer than 2 characters
.filter(text => text.length > 2)
// Pause for 350ms
.debounceTime(350)
// Only if the value has changed
.distinctUntilChanged()
.flatMap(search => this._autocompleteService.autocomplete(this.url, search)).subscribe((result) => { /* Values to be shown in the dropdown */ }}

Let’s say we would now edit the value of the input like this:

this.input.setValue(selectedDropDownItem);

This would trigger the valuechanges to go off and return a new result in the dropdown. This is behavior is something that we don’t want.

Solution

To avoid the valuechanges to go off we can use the following options:

this.input.setValue(selectedDropDownItem, {emitEvent:false});

emitEvent: When true or not supplied (the default), both the statusChanges and valueChanges observables emit events with the latest status and value when the control value is updated. When false, no events are emitted.

Now our users can select the dropdown without getting a new list in the dropdown!

Thanks for reading, leave a comment if you have any questions!

--

--