Angular ngbTypeahead 不会在模糊时重置输入值

Angular ngbTypeahead doesn't reset value of input on blur

我正在使用 Angular2+ 的 bootstrap ngbTypeahead,我想在失去焦点且没有项目 selected 时清理输入。

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

像这样:

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 个或更多字符进行测试。

我使用的解决方案是覆盖 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