I'm using the bootstrap ngbTypeahead of Angular2+ and I want to clean the input when lose focus and no item ware selected.
But the value doesn't clean when the typeahead shows options to select, even if I lose the input focus and dont select any item.
Like This:
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('');
}
}
This strange thing happens too:
Running Sample: https://stackblitz.com/edit/angular-ivy-spzwkm
PS: Type 3 or more characteres to test.
The solution that I used was override the function dismissPopup()
of NgbTypeahead
.
Like this:
import { NgbTypeahead } from '@ng-bootstrap/ng-bootstrap';
constructor(...) {
NgbTypeahead.prototype.dismissPopup = function() {
if (this.isPopupOpen()) {
this._closePopup();
if (this._elementRef.nativeElement.value !== '') {
this._writeInputValue(this._inputValueBackup);
}
}
}
}
Running Sample: https://stackblitz.com/edit/angular-ivy-i8omg9