简体   繁体   中英

ng bootstrap typeahead not working with angular reactive form

Here is my component file

import {NgbTypeahead} from '@ng-bootstrap/ng-bootstrap';
import { map, switchMap, finalize, debounceTime, distinctUntilChanged, filter } from 'rxjs/operators';
import { Subject, merge } from 'rxjs';

const states = [.....]

// inside class
@ViewChild('instance', {static: true}) 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))
);
}

And in my html i use reactive form binding

<input
    id="typeahead-focus"
    type="text"
    class="form-control"
    formControlName="userAssigned" 
    [ngbTypeahead]="search"
    (focus)="focus$.next($event.target.value)"
    (click)="click$.next($event.target.value)"
    #instance="ngbTypeahead"
    />

also initialized my form inside ngOnInit() like this

this.form = this.fb.group({
  userAssigned: ['', Validators.required],
});

When i run this code and click on the input, i am getting the result in pop but getting this error. Also unable to get result when i clear the first result.

在此处输入图像描述

Please help.

the problem is that when search function is declared, "instance is undefined". This happens eg if we has some like

<div *ngIf="form" [formGroup]="form">
...
</div>

The solution is add this.instance in the filter, becomes like this.instance &&.this.instance.isPopupOpen

So, the completed function search is

    search = (text$: Observable<string>) => {
    const debouncedText$ = text$.pipe(debounceTime(200), distinctUntilChanged());
    const clicksWithClosedPopup$ = this.click$.pipe(filter(() => 
      this.instance && !this.instance.isPopupOpen())); //<---HERE
    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))
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM