Avoid showing the previous list with mat-autocomplete

Using this script, I have successfully implemented the addition of <mat-option> tags:

HTML

    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option (onSelectionChange)="onEnter($event)" *ngFor="let data of technologies" [value]="data.technology">
        <span matBadge="{{data.counter}}" matBadgeOverlap="false">{{data.technology}} </span>
      </mat-option>
    </mat-autocomplete>

TS

    // When a key is pressed, display technologies
     onKeyUp(event: any): void {
      if (event.target.value.trim().length > 0) {
        this.technologiesService.getTechnologies(event.target.value)
          .subscribe(data => {
            if (JSON.stringify(this.technologies) !== JSON.stringify(data)) {
              this.technologies = data;
            }
          });
      }

The issue at hand

Upon pressing a key, a list of options is displayed. Subsequent key presses result in the same list (array technologies) being shown briefly before disappearing and being replaced by the new list after about one second.

It may be due to the time required for the new data to be fetched from the server. How can I ensure that ONLY the new list is displayed without this brief transition?

Answer №1

Indeed, the updated list will not be displayed until the data is received. You can initialize this.technologies as an empty array.

You are dealing with two streams in this case - API calls and keyup events. It would be beneficial to merge them into a single stream for better control and easier implementation of additional features (such as debounceTime, loading animation, etc.):

@ViewChild('auto', {static: false}) matAutocomplete: ElementRef<HTMLInputElement>;

fromEvent(this.matAutocomplete.nativeElement, 'keyup').pipe(
  switchMap(event => {
    this.technologies = [];
    return this.technologiesService.getTechnologies(event.target.value)
  })
).subscribe(data => {
  if (JSON.stringify(this.technologies) !== JSON.stringify(data)) {
    this.technologies = data;
  }
})

This logic should be implemented in ngAfterViewInit() to access the reference to this.matAutocomplete (and make sure to use @ViewChild() for it).

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

Infinite Loop Issue in Angular2 RC5 when using the templateUrl

Encountering an issue with Angular2 RC5 that seems to be causing an infinite loop problem. The app.component, which is bootstrapped by the app.module, appears quite simple: @Component({ selector: 'my-app', template: `TEST` }) export cl ...

Struggling with my initial Angular 2 project, having trouble showcasing data from an object. Any assistance would be greatly

As a newcomer to Angular 2, I am currently in the learning phase and utilizing tutorials and documentation from the official website. Below is the code snippet that I have been working on: import { Component } from '@angular/core'; export class ...

Error: Typings: Invalid syntax - Unexpected symbol =>

Every time I run a typings command, I encounter the following error: AppData\Roaming\npm\node_modules\typings\node_modules\strip-bom\index.js:2 module.exports = x => { ^^ SyntaxError: Unexpected tok ...

Angular4 Error: Unable to link to 'ngClass' as it is not recognized as a property of 'input'

Currently, I am facing an issue in my project where I am utilizing lazy loading. Specifically, within my registration module, I am attempting to utilize the [ngClass] directive to append an 'invalid' class when there are validation errors present ...

The mysterious case of TypeScript imports making all other code vanish

I have multiple classes located in root/app/providers/engine/engine.ts. In my test specification file spec/engine/engine-spec.ts (the spec/ directory is also where the jasmine support/ resides), I have a simple test: ///<reference path="../../typings/g ...

Why is the ngx slick carousel not functioning properly within the ngx-bootstrap accordion in Angular 7?

I am trying to incorporate the ngx-slick-carousel inside an ngx-bootstrap accordion and tabs. The tabs are located within the accordion, but when I try to add the carousel outside of the accordion, it works fine. How can I successfully add it inside the ...

Global error handling fails to catch re-thrown HTTP errors in rxjs throwError scenario

Purpose: Implementing a global error handler for server errors and application errors generated in Typescript code. Approach: Utilizing a custom ErrorHandler from a library project within the same workspace. The library structure is as follows: https://i ...

Example of binding a popup to a geoJSON feature

Currently, I have successfully overlayed geojson data on a map, but I would like to enhance the user experience by allowing them to click on an area and view detailed information in a popup. I tried using the example provided on Leaflet's website: L.g ...

What could be causing Bootstrap to fail in my Angular implementation?

It seems like I have successfully imported everything... angular.json: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects ...

Error alert: Ionic detected a SyntaxError due to a missing closing parenthesis on the emulator

When using Ionic, I encountered an error Uncaught SyntaxError: missing ) after argument list on the emulator, but everything runs smoothly with the serve command: Fetch(what, callbackf) { return this.woo.getAsync(what).then( (result)=> { th ...

Tips for converting the iterator from a v-for to a string within a v-if

I am seeking to comprehend how to utilize v-for with v-if's in order to generate repeated teasers without resorting to more simplistic vue-logic. Currently, it appears that when using v-for with v-if nested within, it is not feasible to assign the ind ...

Notification from the background has been received and parameters have been restored

Sending a post request from "angular->port 4200" to "expressjs server->port 8000". Referencing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts Encountering two errors: 1) Undefined ...

Avoid pressing on y mat-button-toogle

In my component, I have a button-toggle like this: <mat-button-toggle-group appearance="legacy"> <mat-button-toggle *ngFor="let session of sessionsArray!"> <fa-icon icon="calendar-alt"></fa-icon> ...

Navigating the process of downloading files in Angular

As I delve into the world of Angular, I am faced with the challenge of understanding how an address is routed within an application to trigger the download of a file stored on the backend database. Even after executing a window.open command, I remain cluel ...

When constructing a parameter, providers are unable to resolve another provider

I am currently working on an Ionic v3 app and I have encountered an issue with resolving providers within two other providers. Below is the error message I received: Uncaught Error: Can't resolve all parameters for DialogueMetier:([object Object], [ ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Customize the hover colors of dropdown items in mdbootstrap's dropdown menu

I recently customized an Angular MDBoostrap navigation bar using SCSS. I encountered an issue when adding a dropdown tab - the font color and background color both change to white 'on-hover,' similar to this example. <!-- Links --> <ul ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

A fresh perspective on incorporating setInterval with external scripts in Angular 7

Incorporating the header and footer of my application from external JavaScript files is essential. The next step involves converting it to HTML format and appending it to the head of an HTML file. private executeScript() { const dynamicScripts = [this.app ...

changing the sequence of key positions in an array of Objects can be done by specifying the desired key

I'm currently working on an export feature, but the data being received from the API is not in the correct sequence (the keys of the object are in an array). I need to rearrange the keys in the object so that they are in the desired order for a single ...