Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ng bootstrap typehead pass additional parameter

How to pass form array index to getCities function in ng-bootstrap typehead including current input text. Consider 3 is form array index.

address.component.html

<input name="city" type="text" id="city" formControlName="city" [ngbTypeahead]="getCities">

address.component.ts

getCities = (text$: Observable<string>) =>
    text$
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(query =>
        query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
            return Observable.of([]);
        });)
like image 857
Rajasekar D Avatar asked Dec 13 '22 19:12

Rajasekar D


1 Answers

It sounds like you are needing to pass an additional parameter to the ngbTypeahead function (be it an index parameter or otherwise).

While the documentation ( https://ng-bootstrap.github.io/#/components/typeahead/api ) does not provide for passing parameters, you can implement a "factory" method that returns an appropriate function with the index (or whatever) parameter passed in.

address.component.html

    <input name="city" 
        type="text" 
        id="city"
        formControlName="city"
        [ngbTypeahead]="searchFunctionFactory($index)" >

address.component.ts

    //A function that returns a "search" function for our ngbTypeahead w/ "preloaded" parameters
    public searchFunctionFactory($index: any): (text: Observable<string>) => Observable<any[]> {


        //Create a function that considers the specified $index parameter value
        let getCities = (text$: Observable<string>) => 
            text$
                .debounceTime(300)
                .distinctUntilChanged()
                .switchMap( query => {

                    //some logic involving $index here
                    //...

                    //query.length < 2 ? [] : this.apiService.getCities(query).catch(() => {
                    //return Observable.of([]);
                });

        //Return that "custom" function, which will in turn be called by the ngbTypescript component
        return getCities;
    }
like image 130
MattEvansDev Avatar answered Dec 31 '22 12:12

MattEvansDev