我使用的是bootstrap的 ngbTypeahead Angular2+的,我想在失去焦点且没有选择任何项目时清理输入。
但是,当typeahead显示选项选择时,即使我失去了输入焦点并且没有选择任何项目,该值也不会被清除。
像这样。
HTML:
<input type="text"
id="obj"
formControlName="obj"
class="form-control"
[class.is-invalid]="searchFailed"
[ngbTypeahead]="filter"
(selectItem)="selectObj($event.item)"
(blur)="blurObj()" />
Typescript:
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.comeditangular-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);
}
}
}