Reactivity in Angular Autocomplete with API Integration

I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete dropdown. Everything seems to be working fine, however, after loading the last request from the service, I noticed that I need to perform an action (such as clicking or typing) in order to view the last result from the response in the autocomplete dropdown. Interestingly, when I tested this on a new Angular project, I did not encounter this issue. Just for reference, my Angular version is 10.

The code snippet responsible for loading the data is as follows:

// Search a place
search = new FormControl();
body: any;
isLoading: boolean;
errorMsg: string;
filteredPlace: any;
places = [];
minLengthTerm = 2;
selectedValue = '';
@ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;    

this.search!.valueChanges.pipe(
    distinctUntilChanged(),
    debounceTime(500),
    tap(() => { 
        this.places = [];
    }),
    filter(value => value ? true : false),
    switchMap(search => 
        this.placeService.searchPlace(search).pipe(catchError(() => of([])))
    )
).subscribe((val) => {
    this.places = val;
    console.log(val);
    if (this.places.length === 0) {
        // If no result we show the possibility to create a place
        console.log(('No Data'));
        this.autocomplete.closePanel();
    }
})

onSelResult(option: any){
    this.selectedValue = option.name;
    console.log(option);
}

clearSelection() {
    this.selectedValue = '';
    this.places = [];
}

The corresponding HTML code:

<mat-form-field appearance="fill">
    <mat-label>Rechercher un lieu</mat-label>
    <input 
      matInput
      placeholder="Type de lieu, nom, adresse, département, code postal, ville" 
      [formControl]="search"
      [matAutocomplete]="auto"
      [value]="selectedValue">
      <button
        matSuffix mat-icon-button  
        aria-label="Clear" (click)="clearSelection()">
        <mat-icon>close</mat-icon>
      </button>
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let place of places" (onSelectionChange)="onSelResult(place)">
          <span><b>{{place.name}}</b> ({{place.zipCode}})</span>
        </mat-option>
    </mat-autocomplete>
    <mat-hint>
      Vous pouvez séparer par des virgules pour lancer la recherche sur plusieurs champs. <b>Exemple : Cimetière, 95</b>
    </mat-hint>
  </mat-form-field>

I'm puzzled as to why an action is needed to view the latest result of my request (an array of objects) in the autocomplete dropdown.

I attempted to fetch the data in an Observable before setting up the autocomplete and utilized the async pipe in the HTML, but unfortunately, the data does not update based on valueChanges with this approach. Even when trying to update the observable post switchMap, the issue persists.

Any advice would be greatly appreciated. Thank you.

Answer №1

After searching extensively, I stumbled upon this amazing example that includes a filter for the results, and it works perfectly.

Check out the demo here!

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

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

What is the mechanism behind the widening of object literal types in Typescript inference?

I've been reading up on how typescript broadens inferred types but I'm still not entirely clear about what's happening here: type Def = { 'T': { status: 5, data: {r: 'm'}}, } function route<S extends keyof Def> ...

Issue with Angular 12.1: Unable to retrieve value using "$event.target.value"

I am just starting to dive into the world of Angular and have been using YouTube tutorials as my guide. However, I have encountered an error in one of the examples provided. Below is the code snippet that is causing me trouble. HTML <input type=" ...

Apollo useQuery enables risky array destructuring of a tuple element containing any value

Currently, I am incorporating TypeScript into my project and have a GraphQL query definition that utilizes Apollo's useQuery. According to the documentation, the call should be typed, however, I am encountering an ESLint error regarding data being ass ...

Ways to access configuration settings from a config.ts file during program execution

The contents of my config.ts file are shown below: import someConfig from './someConfigModel'; const config = { token: process.env.API_TOKEN, projectId: 'sample', buildId: process.env.BUILD_ID, }; export default config as someCo ...

uninstall angular cli from all environments

Hey there! I've attempted to remove the global @angular/cli from my system, but even after doing so, the 'ng -v' command still gives me a warning message: "Your global Angular CLI version (1.7.0) is greater than your local." Here's wha ...

Tips for troubleshooting or modifying a dependency that exclusively consists of type declaration files

I am currently facing a challenge where I need to access and debug/change the code of one of our dependencies that contains custom Angular components from a separate repository. This particular repository is being included via a self-hosted npm registry wi ...

Upon attempting to run ionic for iOS, an error was encountered regarding the arm64 and armv7 architectures

I'm currently in the process of developing a mobile application for both Android and iOS platforms utilizing Ionic version 1. Here is a breakdown of the software versions I'm working with: cordova: 7.0.1 ionic: 2.2.2 ios-deploy: 1.9.2 ios-sim: ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

how can I display the JSON description based on the corresponding ID using Ionic 3

I have a JSON file containing: [{ "id": "1", "title": "Abba Father (1)", "description": "Abba Abba Father." }, { "id": "2", "title": "Abba Father, Let me be (2)", "description": "Abba Father, Let me be (2) we are the clay." }, { ...

Issue arises when trying to set object members using a callback function in Typescript

I am facing a peculiar issue that I have yet to unravel. My goal is to display a textbox component in Angular 2, where you can input a message, specify a button label, and define a callback function that will be triggered upon button click. Below is the c ...

Guide on utilizing a declaration within a third-party module

I have encountered an issue while using the fingerprintjs2 library, as the declaration provided in DefinitelyTyped seems incomplete and incompatible. In order to resolve this, I decided to create my own declaration within my project. However, I am facing ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Exploring the capabilities of Angular2 and Jasmine through testing

I have been working on a basic spec for a component and I'm curious about the test's behavior. The test is designed to verify if a component is successfully created. It seems that when the test is executed, it first compiles and runs the Compone ...

Performing an Angular 5 JSONP request using custom HttpHeaders

I'm attempting to make a JSONP request with specific HTTP header parameters. Using http.get makes it simple: let header = new HttpHeaders(); header.append(<header_param_name>, <header_param_value>); this.http.get(<my_url>, { header ...

Can we securely retrieve nested properties from an object using an array of keys in TypeScript? Is there a method to accomplish this in a manner that is type-safe and easily combinable?

I wish to create a function that retrieves a value from an object using an array of property keys. Here's an example implementation: function getValue<O, K extends ObjKeys<O>>(obj: O, keys: K): ObjVal<O,K> { let out = obj; for (c ...

Issue with separatorKeys functionality in ng2-tag-input

I've been experimenting with the ng2-tag-input module using a simple configuration: import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'search-form', template: `<tag-input [( ...

Authenticate the user using IdentityServer

I'm looking to set up a system where the user is automatically redirected to the login page after an hour, but I'm having trouble configuring this on my server. I've added both AccessTokenLifetime and AbsoluteRefreshTokenLifetime on my ID se ...

How to make text dynamically shrink with TailwindCSS class 'flex-shrink-0'

I've designed an 'Album' (React) component to showcase album artwork, name, and release date in a card-like format. This component consists of two divs - one for the photo and the other for text. Each artist's discography displays multi ...