Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question.

I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint:

  • GET /person/name/{name}

This endpoint returns a list of people matching the specified name, with each person having the structure:

Person(id:long, name:string, surname:string)

Currently, everything works fine when I map(...) the array of persons to an array of string names within the _service:

  • [p1, p2, p3] -> [nameP1, nameP2, ...]

However, instead of mapping the names in the _service, I want to return the list of persons so that users can click on a result in the dropdown and see the person's details without making additional calls.

In my typescript component, the model is:

model: Observable<Person[]>;

The search function looks like this:

search = (text$: Observable<string>) =>
        text$.pipe(
            debounceTime(300),
            distinctUntilChanged(),
            tap(() => this.searching = true),
            switchMap(term =>
                this._service.search(term).pipe(
                    tap(() => this.searchFailed = false),
                    catchError(e => {
                        this.searchFailed = true;
                        return of([]);
                    }))
            ),
            tap(() => this.searching = false),
            merge(this.hideSearchingWhenUnsubscribed)
        )

And here is the HTML part:

<div class="input-group input-group-lg" id="person-search">
        <input name="name" id="typeahead-http" type="text" class="form-control" [class.is-invalid]="searchFailed" (selectItem)="selectedItem($event)" [(ngModel)]="model" [ngbTypeahead]="search" placeholder="Search a person"/>
        <span class="input-group-btn">
            <button class="btn btn-primary btn-lg" type="button">
              <i class="text-muted fa fa-search"></i>
            </button>
        </span>
  <div>

How can I display only the names in the dropdown and allow users to click on a name to view the corresponding person?

Answer №1

To display the name correctly, you must utilize a resultFormatter to show the name and an inputFormatter to only display the name when selecting a value. Failure to do so will result in [object Object] being shown in the input field. Both formatters are provided by the typeahead feature.

In your TypeScript file, specify that you want to present the name in both the results and input:

formatter = (x: { name: string }) => x.name;

Then, use these formatters in the template as follows:

<input ... [resultFormatter]="formatter" [inputFormatter]="formatter"/>

Even though your model will still contain the entire object, the correct formatting will ensure that only the name is displayed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array. Array cars = [{ id: 1, ...

Troublesome Deployment of Angular on IIS 7.5: Why It's Not Going

My Angular project deployment is experiencing issues with a missing component. Workflow Step 1: I ran the following command: ng-build --prod Step 2: I added the website to IIS using the path inside dist. Step 3: The index page functions correctly, ...

Oops! Angular2 couldn't find a provider for HttpHandler

I have been working on implementing HttpCache through an interceptor. Below is the code snippet for caching-interceptor.service.ts: import { HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http' import ...

What is the best way to reference typescript files without using absolute paths?

As typescript does not seem to have built-in support for absolute path references (according to this GitHub issue), it becomes difficult to organize and maintain my file references. With TypeScript files scattered across various locations in my folder stru ...

What is the best way to retrieve the file path of a imported Angular module?

I am trying to figure out how to retrieve the path of the BarComponent within the code snippet below. Specifically, I need to obtain '../bar/bar.component'. When dealing with a module loaded from a package such as Component module, I would like t ...

Incorporate Sendbird into Angular 6 for seamless communication integration

I recently started delving into the world of angular6 and nodejs. I am eager to integrate sendbird with Angular6, but I'm struggling to find a clear starting point. If anyone has successfully done this before, I would greatly appreciate some guidance ...

What is the best way to showcase a diverse list with varying templates using Angular?

Looking to showcase a variety of items sourced from a service, each potentially belonging to different types. I am in search of a way to dynamically display distinct templates for each item based on its value or type. Is there a functionality that allows ...

How to send a value to a function in Angular from a different function?

Within my Angular Typescript file, I am working with two functions named data and lists. My goal is to pass the variable windows from the function data to the function lists. However, when attempting to call the function lists, I encounter an error: Canno ...

How can the NavBar be refreshed once a user logs in?

I recently followed a helpful guide on implementing a login system in my React TS application. However, I encountered an issue with the NavBar component within my app compared to how it was coded in the App.tsx file of the guide. Specifically, I found it c ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

Angular 2 ngx-modal: A User-Friendly Modal Component

I have encountered an issue while trying to implement a modal form in my Angular application. Even though my code seems correct and I have installed ngx-modal as well as imported the ModalModule in my app.module.ts, the modal form is not responding. Any ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

What is the best way to combine TypeScript output while maintaining node import integrity?

Currently, I am combining the results of the typescript compiler using this particular technique. However, this process is causing issues with the imports of relative path modules in Node. The code below compiles and merges successfully; // Group.ts clas ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

The application is having trouble accessing the property 'isXXXXX' because it is undefined

My attempt to utilize a shared service in one of my components has been successful when used with the app's root component. However, I encountered an error when trying to implement it on another module or dashboard. shared/authorize.service.ts @Inje ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...

Issue with accessing the 'subscribe' property in nested calls within Angular 2 due to it being undefined

I am trying to implement a subscription in company-list.component using the method getCompanies() from the company.service. However, I am encountering the following error: Cannot read property 'subscribe' of undefined Here is the code snippet ...

I am currently working on establishing a connection between Angular and MongoDB

I built a basic Angular application currently running on Local Host 4200. What is the process for saving form values and storing them in a MongoDB database? ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...