如何在Angular 2中编辑Form Control值时不发出事件

ben*_*d-g 9 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)
      );
}
Run Code Online (Sandbox Code Playgroud)

_autocompleteService将搜索请求发送到服务器并返回一个字符串数组.

我的html模板看起来就是这样.它显示了输入下的建议列表,其中可以选择每个元素.

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

这是选择功能:

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;
}
Run Code Online (Sandbox Code Playgroud)


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

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

Per*_*xel 18

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

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;
}
Run Code Online (Sandbox Code Playgroud)

emitEvent: false 将阻止valueChanges事件被发出.

如果emitEvent为true,则此更改将导致FormControl上的valueChanges事件被发出.默认为true(因为它落到updateValueAndValidity).

  • @Pylinux - 我认为这不取决于浏览器.我的Chrome被忽略了...... (6认同)
  • 还有其他人在firefox中忽略了`{emitEvent:false}`的问题吗? (4认同)
  • 我注意到当值设置为“null”或“undefined”时它可能不起作用 (3认同)