Angular 2 ng bootstrap typehead pass additional parameter

我们两清 提交于 2019-12-04 02:17:49

问题


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([]);
        });)

回答1:


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;
    }


来源:https://stackoverflow.com/questions/47314751/angular-2-ng-bootstrap-typehead-pass-additional-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!