如何在Angular 2

时间:2016-10-04 16:31:04

标签: angular

我正在尝试使用Angular2和Form Control编写自动完成输入字段。

首先,我决定将表单控件初始化为:

  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模板看起来就是这样。它显示了输入下的建议列表,其中可以选择每个元素。

  <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;
  }


这是问题所在。 当我编辑术语的值时,它会发出一个事件并发送一个新的搜索请求,显示一个新的建议列表。

有没有办法防止这种事件发生,只是改变输入中显示的值?

1 个答案:

答案 0 :(得分:14)

根据docs,您可以执行以下操作:

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为true,则此更改将导致FormControl上的valueChanges事件被发出。默认为true(因为它落到updateValueAndValidity)。