Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component:

export class PostComponent {

  selectedCategoryID: number;

  allCategories$: Observable<CategoryModel[]>;

  constructor(private catService: CategoryService) { }

  ngOnInit() {

    this.allCategories$ = this.getCategories('');

  }

  getCategories(typedTerm: string): Observable<CategoryModel[]> {

    return this.catService.fetch(typedTerm).pipe(map((envelop: Envelope<CategoryMessage.Response>) => 

      envelop.data.map((response: CategoryMessage.Response) => { 

        return {
          id: response.id, 
          name: response.name
        };

      })));

  }

}

The service catService retrieves categories where the term is found in the category name.

In the template, I have the following:

<ng-select 
   class="select"
   [items]="allCategories$ | async"
   [addTag]="true"
   bindLabel="name"
   bindValue="id"
   [multiple]="false"
   [(ngModel)]="selectedCategoryID">
</ng-select>

Inquiry

  1. How can I efficiently call the API through the service only when the user types 3 or more letters to avoid overwhelming data retrieval?

  2. Is there a way to incorporate typeahead functionality into my existing code?

Answer №1

Snippet:

<ng-custom-select 
   class="custom-select"
   [items]="categoriesList$ | async"
   [allowNewTag]="true"
   bindLabel="name"
   bindValue="id"
   [multipleSelection]="false"
   [(selectedItem)]="selectedCategoryID"
   (selectionChange)="onSelectionChange($event)">
</ng-custom-select>

Angular code:

public onSelectionChange(inputTerm) {
   if (inputTerm && inputTerm.length >= 3) {
      this.retrieveCategories(inputTerm).subscribe(categoriesList => {
         // Your logic can go here...
      });
   }
}

UPDATE: Consider utilizing the debounce feature to reduce excessive requests while typing. Take a look at this helpful example.

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

What is the best way to implement an asynchronous function using a for loop and APIs in Typescript?

Struggling with ensuring my function returns data only after completing all API calls and the for loop. getListingsImages(sessionID, mlsSearchCriteria){ this.http.get(this.laconiaBaseURL + "mls/search/" + sessionID + "?" +querySt ...

Error message "NoSuchKey" encountered on CloudFront when accessing an Angular application

I recently developed an Angular application and successfully uploaded it to an S3 bucket. To make my website accessible, I deployed a CloudFront distribution. However, when trying to access a specific route on the website (such as /login), I encountered an ...

Angular Service worker mishandles http redirects (302)

In my current project, I am implementing Angular and Spring Boot technologies. When I build the project, Angular generates the service worker for me. The issue arises when I use an external service (auth2) and my backend redirects to the login page after ...

Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values: { "message.key": "First value is {{0}} and se ...

Validation in Sync with Angular 2's Latest Version

Encountering the error 'Expected validator to return Promise or Observable' when trying to implement a custom synchronous validator using FormControl and FormGroup classes for validation. The transition from beta to final release has been baffli ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...

Encountering issues when integrating an Angular library project into the main project

Currently, I am facing an issue with a library project (let's call it X) that contains 2 projects within it (X-core, X-core-members). My goal is to utilize this library in another angular project called ABC. I have made the necessary links in the tsco ...

Dynamically adjust the label position based on the button position

I am currently developing an interface that allows users to change the position of buttons and add a label text under the button. However, I am facing an issue where the label is not always centered below the button due to variations in the size and number ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

Is it possible for me to listen to an AngularJS event using regular JavaScript, outside of the Angular framework?

Is it possible to listen to an event triggered in AngularJS using regular JS (outside of Angular)? I have a scenario where an event is being emitted using RxJS in Angular 2. Can I observe that event from pure JS? Here's some example pseudo code: imp ...

Angular: Initiate multiple functions simultaneously and combine results afterwards

My current code successfully zips and saves the response of a JSON array by splitting them into individual files using a single method. zip: JSZip = new JSZip(); folder: JSZip = new JSZip(); this.apicall.api1() .subscribe( response => { for (let r ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Why would npm be unable to locate a file, potentially leading to an error? Could the lack of contents in my node_modules subfolder be the root cause of this issue?

I'm encountering an issue while attempting to execute npm install in the angular project directory obtained from ASP.NET Boilerplate. The error I'm facing is related to npm's inability to locate a specific file. D:\Dev\AspNetBoiler ...

The custom form input in Angular2 is throwing an error because it is trying to access the property 'name' of an

Upon switching to the latest Angular version 2 final, I encountered the following error Uncaught TypeError: Cannot read property 'name' of undefined This is my customized input import { Component, EventEmitter, Provider, forwardRef } from &a ...

Troubleshooting Angular2 component testing: Why is Karma not loading the templateUrl?

As I work on writing tests for my Angular2 application, I am encountering a problem. When I use the templateUrl property in the Angular2 component, linking it to an HTML file, instead of using the template property, the test fails to run. The async callbac ...

Unable to personalize map controls in OpenLayer mapping system

Having trouble styling custom map controls with CSS selectors .ol-zoom-in and .ol-zoom-out. Any suggestions on how to customize them? export class CustomMapControlsComponent implements OnInit { map: Map | undefined; constructor() {} ngOnInit() ...

What is the reason behind Angular FormControl applying the 'disabled' attribute in the DOM but not the 'required' attribute?

After transitioning my form logic from the template to FormGroup & FormControl objects, I noticed that when a FormControl is disabled in Angular, the 'disabled' attribute for the field is automatically updated in the DOM. However, when I modi ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Issue with Angular 2 HTTP provider: Observable subscription not triggering

I'm struggling to trigger the .subscribe() method on an observable in Angular 2. I have a provider that uses the Http Service to fetch data and return an observable for the controller to subscribe to. I can't figure out why the subscribe functio ...