我使用ng-bootstrap 4(beta 8)。目前我有这个:
<ng-template #rt let-r="result" let-t="term">
{{ r.label }}
</ng-template>
<input
id="typeahead-focus"
class="form-control"
[(ngModel)]="model"
[ngbTypeahead]="search"
[inputFormatter]="formatter"
[resultTemplate]="rt"
(focus)="focus$.next($event.target.value)"
(click)="click$.next($event.target.value)"
#instance="ngbTypeahead"
/>
现在,如果用户单击input元素,我想打开typeahead。我怎么能这样做?
this.search = (text$) =>
text$
.map(term => (term === '' ? this.items : this.items.filter(v => v.label.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10));
this.formatter = (x: {label: string}) => {
console.log(x);
return x.label;
答案 0 :(得分:5)
以下解决方案适合我:
将onFocus
事件添加到您的输入搜索
my.html文件
<input
(focus)="onFocus($event)"
type="text"
(selectItem)="onItemSelected($event)"
[(ngModel)]="myModel"
[ngbTypeahead]="search"
[resultTemplate]="rt"
[inputFormatter]="formatter"/>
my.ts文件
public onFocus(e: Event): void {
e.stopPropagation();
setTimeout(() => {
const inputEvent: Event = new Event('input');
e.target.dispatchEvent(inputEvent);
}, 0);
}
search = (text$: Observable<string>) =>
text$
.debounceTime(200)
.distinctUntilChanged()
.map(term => this.myList
.filter(v => this.myfilter(term))
.slice(0, 10));
答案 1 :(得分:0)
根据当前的documentation,您可以使用html:
<input id="typeahead-focus" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" (focus)="focus$.next($event.target.value)" (click)="click$.next($event.target.value)" #instance="ngbTypeahead"/>
和代码:
@ViewChild('instance') instance: NgbTypeahead;
focus$ = new Subject<string>();
click$ = new Subject<string>();
search = (text$: Observable<string>) => {
const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
const clicksWithClosedPopup$ = this.click$.pipe(filter(() => !this.instance.isPopupOpen()));
const inputFocus$ = this.focus$;
return merge(debouncedText$, inputFocus$, clicksWithClosedPopup$).pipe(
map(term => (term === '' ? states
: states.filter(v => v.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))
);