What could be the reason for mat-autocomplete not displaying the loading spinner?

Currently, I am integrating Angular Material into my Angular 11 project. One of the pages includes a mat-autocomplete component where I want to display a loading spinner while waiting for a request. Here is the code snippet I am using:
component.ts

this.searchServiceProviderCtrl.valueChanges
    .pipe(
        debounceTime(500),
        tap(() => {
            this.loading = true;
        }),
        switchMap((value) => this.serviceProviderAutocompleteService.searchByQuery(value)
        )
    )
    .subscribe((response) => {
        this.serviceProviders = response;
        if (isNullOrUndefined(this.serviceProviders) || this.serviceProviders.length === 0) {
            this.emptyServiceProviders = true;
            this.loading = false;
        }
    });

component.html

<mat-form-field>
        <input matInput placeholder="Search" aria-label="State" [matAutocomplete]="auto" [formControl]="searchServiceProviderCtrl">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngIf="loading" class="is-loading">
            <mat-progress-bar mode="indeterminate"></mat-progress-bar>
          </mat-option>
          <mat-option *ngIf="emptyServiceProviders">No results</mat-option>
          <ng-container *ngIf="!loading">
            <mat-option *ngFor="let serviceProvider of serviceProviders" [value]="serviceProvider">
              <span><b>{{serviceProvider.lastName + ' ' + serviceProvider.firstName}}</b></span>
            </mat-option>
          </ng-container>
        </mat-autocomplete>
    </mat-form-field>

Initially, I did not see the loader, and upon investigation, I realized that my service was synchronous. To simulate a delay, I added a portion of non-functional code with a sleep(5000ms) effect:

    searchByQuery(query: string): Observable<any[]> {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < 5000);
    return of(this.values.filter((v) => v.firstName.toLowerCase().indexOf(query.toLowerCase()) > -1 || v.lastName.toLowerCase().indexOf(query.toLowerCase()) > -1));
}

Even with this workaround, I still did not see the loading spinner. To debug, I added {{loading}} in the HTML, and it never changed to true despite the tap() => this.loading = true being called. Can anyone suggest why the loading boolean is not updating in the HTML?

Answer №1

Your search function is currently synchronous because it uses a busy wait, causing the browser tab to become unresponsive for 5 seconds, and the spinner fails to display.

To convert the search function to asynchronous using Rxjs, you can implement the following code snippet:

import { delay} from 'rxjs/operators';

search(query: string): Observable<any[]> {
    return of(this.items.filter((item) => item.name.toLowerCase().indexOf(query.toLowerCase()) > -1))
        .pipe(delay(5000));
}

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

Using Angular 2 to toggle the visibility of a component when hovering over and moving away from it

I have developed a custom filtering component in Angular 2, which I have integrated into the table header. My goal is to show the filter when the mouse hovers over a specific span, and hide it when the mouse moves away. <th> <span class="headCol ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Creating a Custom TreeView in VS Code using JSON data

My goal is to create a TreeView using data from a JSON file or REST call, with custom icons for each type of object (Server, Host, and Group). I want to implement configuration.menu similar to the dynamic context menu discussed in this thread. I am relati ...

Count of items in filtered data displayed using Angular 5 *ngFor

Looking for help with my ngFor loop: *ngFor="let item of items | filterBy: ['SN', 'Name']: userFilter | orderBy: order | paginate: {itemsPerPage: 10, currentPage: 1}; let i = index;" Trying to retrieve the count of filtered items. Whe ...

Tips for retrieving a specific key/value pair during an Http request in Angular

After making an HTTP call, I received a JSON file with the following data: [ { "totalConfirmed": 555, "mainlandChina": 548, "otherLocations": 7, "deltaConfirmed": 555, "totalRecovered": 0, "confirmed": ...

Attempting to grasp the concept of Typescript generics

I have a function defined as follows: interface ExtraModels extends Model { unknown: string } const write = async (data: ExtraModels[]) => { console.log(data[0].unknown) } This function is currently working. However, I want to modify it to: cons ...

Use a pipe to show the content of the md-input

In my Angular 2 Material application, I have a form that includes a price input: <md-input [(ngModel)]="price" placeholder="Price"> </md-input>{{price|customCurrency}} This input field uses a custom version of the CurrencyPipe which you c ...

Is it possible to record the attributes within an interface in TypeScript?

Imagine I have the following scenario: interface Validator { validate: (value: string) => boolean; errorMessage: string; } interface EditDialogField { label: string; prop: string; required?: boolean; type: 'input'; validators?: ...

Experiencing issues with the functionality of getServerSideProps in my project

I'm scratching my head over why server-side props aren't working for me in nextjs (v12). I'm utilizing getServerSideProps inside pages/details/index.tsx. export const getServerSideProps = async (context: any) => { const name = context.q ...

A guide on converting array values to objects in AngularJS HTML

Here is my collection of objects: MyCart = { cartID: "cart101", listProducts : [ {pid:101, pname:"apple", price: 200, qty:3}, {pid:102, pname:"banana", price: 100, qty:12} ] } I have incorporated a form in ...

The process of unit testing a component to verify the presence of a specific component on the page

Presenting my straightforward custom component dubbed as NavbarComponent with the selector app-navbar. This component serves as a basic static navbar and is being displayed in app.component.html: app.component.html <app-navbar></app-navbar> &l ...

Tips for directing your attention to an input field in Angular

I'm struggling to find a simple solution for setting focus programmatically in Angular. The closest answer I found on Stack Overflow is about dynamically created FormControl, but it seems more complex than what I need. My situation is straightforward ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

The ability of Angular 4 ngComponentOutlet to load dynamic components is great, however, there seems to be an issue

Currently, I am faced with the challenge of loading various 'parent' components and injecting route content into these individual parent components by utilizing ng-content in each one. Essentially, the purpose of each parent component is to manag ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

There seems to be an issue with the functionality of Angular Material on iOS devices

I recently developed a website using Angular and Angular Material. While the site functions properly on Windows and Android across all browsers, I encountered an issue with iOS devices running Safari. Some elements on the page do not display correctly on i ...

Unable to simulate the Enter key press event for a text area using Angular 7

I've implemented a feature that allows users to type something and then press the submit button, at which point the cursor should move to the next line. If the user types some words and presses the Enter key, the cursor should also shift to the next l ...

In my Angular 6 project, I am faced with the challenge of having two separate navbars and routes that need to be integrated into the same page

I have two different navigation bars that I need to configure. The first one is the primary navbar, while the second one is for a specific section of the project. I also need to ensure that the second navbar remains visible when a link in the footer is cli ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

What is the process for installing npm dependencies to a specific directory without creating a node_modules folder?

I recently published a package called main-package, which has a dependency on another package called sub-package that is already available on npm. However, when I install main-package, it creates a node_modules folder with both packages at the same level. ...