0

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.

enter image description here

// 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.

1 Answer 1

0

When using typeaheadItemTemplate with complex data (objects rather than strings in the datasource) you are also required to define the typeaheadOptionsField so that the component doesn't try (and fail) to render the whole object in the search field.

// app.component.html
...
<input ...
       [typeaheadItemTemplate]="customItemTemplate"
       typeaheadOptionsField="name">

...

name here is the name of the property on the object, which can be nested or be a function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.