Angular 2 ng bootstrap typehead 传递附加参数

Angular 2 ng bootstrap typehead pass additional parameter

如何将表单数组索引传递给 ng-bootstrap 打字头中的 getCities 函数,包括当前输入文本。考虑 3 是表单数组索引。

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

听起来您需要向 ngbTypeahead 函数传递一个附加参数(无论是索引参数还是其他参数)。

虽然文档 ( https://ng-bootstrap.github.io/#/components/typeahead/api ) 没有提供传递参数的功能,但您可以实现一个 "factory" 方法,该方法 returns 一个适当的函数,并传递索引(或其他)参数英寸

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