I have form with 10 input fields and of those 5 are typeaheads with different sets of data.
My html file looks like this
<input
type="text"
class="form-control text-body"
id="field1"
name="field1"
ngModel
#field1
[ngbTypeahead]="searchField1"
[selectOnExact]="true"
#instance="ngbTypeahead"
/>
<input
type="text"
class="form-control text-body"
id="field2"
name="field2"
ngModel
#field2
[ngbTypeahead]="searchField2"
[selectOnExact]="true"
#instance="ngbTypeahead"
/>
And for each of these input fields, I added separate methods
searchField1 = (text$: Observable<string>) =>
text$.pipe(
map((term) =>
term === ''
? data1
: data1
.filter((v) => v.toLowerCase().indexOf(term.toLowerCase()) > -1)
.slice(0, 10)
)
);
Is there a way to avoid duplicating of code for every typeahead field. I did come across older posts where the search method would accept a param and based on that param the data could be changed.
But it seems with the latest version that functionality is broken. Is there any work around for that.
Below is my attempt at passing a param to the search method but the issue I faced was the typeahead does not filter when user starts typing. But in the console I did see the user entered values getting logged.
searchField = (type:string) => {
let data;
if(type === 'field1') {
data = [a];
} else if (...){}
return (text$: Observable<string>) => {
console.log('text$', text$);
return text$.pipe(
map((term) =>
term === ''
? data
: data
.filter((v) => v.toLowerCase().indexOf(term.toLowerCase()) > -1)
.slice(0, 10)
)
);
};
}
Would be grateful if someone could let me know if there is any work around this issue or if there is any alternate option to avoid creating separate search methods.