【问题标题】:Angular ngbTypeahead doesn't reset value of input on blurAngular ngbTypeahead 不会重置模糊时的输入值
【发布时间】:2020-05-21 00:00:24
【问题描述】:

我正在使用 Angular2+ 的引导程序 ngbTypeahead,我想在失去焦点且未选择任何项目时清理输入。

但是当预先输入显示选项时,该值不会清除,即使我失去了输入焦点并且没有选择任何项目。

像这样:

HTML:

<input type="text"
        id="obj"
        formControlName="obj"
        class="form-control"
        [class.is-invalid]="searchFailed"
        [ngbTypeahead]="filter"
        (selectItem)="selectObj($event.item)"
        (blur)="blurObj()" />

打字稿:

filter = (text$: Observable<string>) => {
    return text$.pipe(
        debounceTime(200),
        distinctUntilChanged(),
        tap(() => this.objSelected = null),
        switchMap( (term: string) => {
          if(term.length < 3) {            
            return [];
          } else {
            this.searching = true;
            return this.service.filter(term as string)
              .pipe(
                tap(() => this.searchFailed = false),
                catchError(() => {
                    this.searchFailed = true;
                    this.searching = false;
                    return [];
                })
              );
          }
        }),
        tap(() => this.searching = false)
    );
}

selectObj(obj: any) {
    this.objSelected = obj;
}

blurObj() {
    if(!this.objSelected) {
      this.form.get('obj').setValue('');
    }
}

这种奇怪的事情也会发生:

运行示例: https://stackblitz.com/edit/angular-ivy-spzwkm

PS:输入 3 个或更多字符进行测试。

【问题讨论】:

  • 更新 ng-bootstrap
  • 我做不到
  • 对不起,现在没时间检查。 editable='false' 有可能解决问题
  • @IAfanasov 没有。那不能解决问题,也没有影响
  • 我试图调查。似乎是 ng-bootstrap 错误。 setTimeout(()=&gt;this.form.get("obj").setValue(''), 1000) 有帮助,而 setTimeout(()=&gt;this.form.get("obj").setValue(''), 100) 没有。停止了它是如此旧版本的 ng-bootstrap 的事实。我 100% 确定您会遇到更多旧错误,这些错误已在新版本中修复,可访问性也是如此。希望能够说服您的团队更新依赖关系

标签: angular bootstrap-4 ng-bootstrap bootstrap-typeahead


【解决方案1】:

我使用的解决方案是重写NgbTypeahead的dismissPopup()函数。

这样:

import { NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';

NgbTypeahead.prototype.dismissPopup = function() {
  if (this.isPopupOpen()) {
    this._closePopup();
    if (this._elementRef.nativeElement.value !== '') {
      this._writeInputValue(this._inputValueBackup);
    }
  }
}

运行示例: https://stackblitz.com/edit/angular-ivy-i8omg9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 2015-01-29
    • 1970-01-01
    • 2020-12-17
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多