Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not emit event while editing a Form Control value in Angular 2

Tags:

angular

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?
like image 575
benard-g Avatar asked Oct 04 '16 16:10

benard-g


People also ask

Which event get triggered when user comes in the form control?

The submit event triggers when the form is submitted, it is usually used to validate the form before sending it to the server or to abort the submission and process it in JavaScript.

How do I turn off form control and keep value?

If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.


1 Answers

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).

like image 60
PerfectPixel Avatar answered Oct 07 '22 00:10

PerfectPixel