如何在ng-bootstrap typehead(包括当前输入文本)中将表单数组索引传递给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([]);
});)
答案 0 :(得分:5)
听起来你需要将一个额外的参数传递给ngbTypeahead函数(无论是索引参数还是其他)。
虽然文档(https://ng-bootstrap.github.io/#/components/typeahead/api)没有提供传递参数,但您可以实现一个“工厂”方法,该方法返回传入索引(或其他)参数的相应函数。
<强> 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;
}