如何在Angular 2中编辑表单控件值时不发出事件 [英] How to not emit event while editing a Form Control value in Angular 2
问题描述
我正在尝试使用Angular2和Form Control编写一个自动完成输入字段.
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将搜索请求发送到服务器,并返回一个字符串数组.
我的html模板看起来是这样的.它在输入下方显示了一个建议列表,您可以在其中选择每个元素.
_autocompleteService send the search request to the server an return an array of strings.
My html template looks this way. It show 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>
这是选择功能:
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;
}
这是问题所在.
当我编辑term的值时,它将发出一个事件并发送一个新的搜索请求,其中显示了新的建议列表.
有没有一种方法可以防止发生此事件,而只是更改输入中显示的值?
Here is the problem.
When I edit value of term, it emit an event and send a new search request which display a new list of suggestions.
Is there a way to prevent this event emission and just change the value displayed in input ?
推荐答案
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
将防止发出valueChanges事件.
emitEvent: false
will prevent the valueChanges event from being emitted.
如果emitEvent为true,则此更改将导致发出FormControl上的valueChanges事件.默认为true(因为它属于updateValueAndValidity).
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).
这篇关于如何在Angular 2中编辑表单控件值时不发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!