【问题标题】:How to not emit event while editing a Form Control value in Angular 2在Angular 2中编辑表单控件值时如何不发出事件
【发布时间】:2016-10-04 16:31:04
【问题描述】:

我正在尝试使用 Angular2 和表单控件编写一个自动完成输入字段。

首先我决定按如下方式初始化我的表单控件:

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

这是问题所在。 当我从 `term` 编辑 `value` 时,它会发出一个事件并发送一个新的搜索请求,然后显示一个新的建议列表。

有没有办法防止此事件发射并仅更改输入字段中显示的值?

【问题讨论】:

  • 引导问题不要放在最后。

标签: angular


【解决方案1】:

根据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)。

【讨论】:

  • 还有其他人有{emitEvent: false} 在 Firefox 中被忽略的问题吗?
  • 我注意到当值设置为nullundefined时它可能不起作用
  • @olahell 我现在遇到了这个问题。我恢复一个值并想忽略更改,但如果我从空选择中恢复该值,它会触发两次。
猜你喜欢
  • 2017-09-25
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 2020-02-20
  • 2018-09-07
  • 1970-01-01
  • 2022-11-28
  • 2016-12-16
相关资源
最近更新 更多