49

I am trying to write an autocomplete input field using Angular2 and Form Control.

First I decided to initialize my form Control as follow:

term = new FormControl();

constructor(private _autocompleteService: AutocompleteService) {
  this.term.valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .flatMap(search => this._autocompleteService.autocomplete(this.urlSearch, search))
      .subscribe(
          autocomplete => this.autocomplete = autocomplete,
          error => console.log(error)
      );
}

_autocompleteService sends the search request to the server and returns an array of strings.

My html template looks like this. It shows a list of suggestions under the input in which each element can be selected.

<input type="text" [formControl]="term">
  <ul>
    <li *ngFor="let suggestion of autocomplete" (click)="selectChoice(suggestions)">{{ suggestion }}</li>
  </ul>

And here is the selection function:

selectChoice(choice: string) {
  this.autocomplete = [];       // We clean the list of suggestions
  this.term.setValue(choice);   // We write the choice in the term to see it in the input
  this.selected = resp;
}

Here is the problem. When I edit `value` from `term`, it emits an event and sends a new search request which then displays a new list of suggestions.

Is there a way to prevent this event emission and just change the value displayed in the input field?
1
  • 3
    Lead with the problem dont put it at the end. Commented Oct 4, 2016 at 17:07

2 Answers 2

81

According to the docs you can do the following:

selectChoice(choice: string) {
  this.autocomplete = [];  // We clean the list of suggestions
  this.term.setValue(choice, { emitEvent: false }); // We write the choice in the term to see it in the input
  this.selected = resp;
}

emitEvent: false will prevent the valueChanges event from being emitted.

If emitEvent is true, this change will cause a valueChanges event on the FormControl to be emitted. This defaults to true (as it falls through to updateValueAndValidity).

Sign up to request clarification or add additional context in comments.

3 Comments

Anybody else have an issue that {emitEvent: false} is ignored in firefox?
I noticed that it might not work when the value was set to null or undefined
@olahell I'm having this issue now. I revert a value and want to ignore the change, but if I revert the value from a null selection, it fires off twice.
1

For those who have the same issue, Try adding onlySelf: true along with the emitEvent: false in this way:

this.term.setValue(choice, { emitEvent: false, onlySelf: true });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.