Is there a solution or a workaround to this?
When one of the options is selected from the typeahead, it appears as "[object Object]". This seems to be a bug with the library when using complex objects with Observables. See this open GitHub issue. This example is a combination of the "Async data" and the "Item template" example from the docs.
// app.component.html
<pre class="card card-block card-header mb-3">Model: {{ asyncSelected | json}}</pre>
<input [(ngModel)]="asyncSelected"
[typeahead]="dataSource"
[typeaheadAsync]="true"
[typeaheadItemTemplate]="customItemTemplate"
class="form-control">
<ng-template #customItemTemplate let-model="item" let-index="index">
<h5>This is: {{model | json}} Index: {{ index }}</h5>
</ng-template>
// app.component.ts
export class AppComponent {
asyncSelected?: string;
dataSource: Observable<any[]>;
statesComplex: any[] = [
{ id: 1, name: 'Alabama', region: 'South' },
{ id: 2, name: 'Alaska', region: 'West' }
];
constructor() {
this.dataSource = new Observable((observer: Subscriber<string>) => {
// Runs on every search
observer.next(this.asyncSelected);
})
.pipe(
mergeMap((token: string) => this.getStatesAsObservable(token))
);
}
getStatesAsObservable(token: string): Observable<any[]> {
const query = new RegExp(token, 'i');
return of(
this.statesComplex.filter((state: any) => {
return query.test(state.name);
})
);
}
}
I'm using Angular 15 and ngx-bootstrap 10.2.0. The FormsModule and TypeaheadModule.forRoot() are imported in the module file.
This question may be related.
