Implement a loading spinner for autocompletion by utilizing an array as data source instead of relying on an

If you're interested in implementing autocomplete using an array instead of an in-memory web API, check out this thread for an example:

Here's the updated search function in autocomplete.service.ts:

search(filter: {name: string} = {name: ''}, page = 1): Observable<IUserResponse> {

  this.commune = {
  total: 4,
  results: [

    { id: 1, name: 'Windstorm' },
    { id: 2, name: 'Bombasto' },
    { id: 3, name: 'Magneta' },
    { id: 4, name: 'Tornado' },
    { id: 5, name: 'Agnosto' }
  ]
}

return of<IUserResponse>(this.commune)
.pipe(
  tap((response: IUserResponse) => {
    response.results = response.results
      .map(user => new User(user.id, user.name))
      .filter(user => user.name.includes(filter.name))

    return response;
  })
  );


 }

This is how the search function is utilized with finalize to intercept observables from http requests:

 async ngOnInit() {

this.usersForm = this.fb.group({
  userInput: null
})

this.usersForm
  .get('userInput')
  .valueChanges
  .pipe(
    debounceTime(300),
    tap(() => { this.isLoading = true }),
    switchMap(value => this.autocompleteService.search({ name: value }, 1)
      .pipe(
        finalize(() => { this.isLoading = false }),
      )
    )
  )
  .subscribe(users => this.filteredUsers = users.results);

}

Answer №1

When utilizing the pipe, one must have an observable. To convert an array into an observable containing data, use of or from from the rxjs library.

The pipe works with the in-memory API because an HTTP call returns an observable.

It is important to note that an asynchronous call is still required for the loader to be displayed. While using detectChanges() may work, it should be a last resort option.

For example, here's a basic illustration based on the material autocomplete documentation that demonstrates how you can simulate the loader by adding a delay of one second to the data retrieval process using delay(1000):

.ts :

@Component({
  selector: "autocomplete-auto-active-first-option-example",
  templateUrl: "autocomplete-auto-active-first-option-example.html",
  styleUrls: ["autocomplete-auto-active-first-option-example.css"]
})
export class AutocompleteAutoActiveFirstOptionExample implements OnInit {
  myControl = new FormControl();
  options: string[] = ["One", "Two", "Three"];
  filteredOptions: string[];
  isSearching = false;

  ngOnInit() {
    this.myControl.valueChanges
      .pipe(
        debounceTime(200),
        tap(_ => this.isSearching = true),
        map(value => this._filter(value)),
        delay(1000),
        tap(data => {
          this.isSearching = false;
          this.filteredOptions = data;
        })
      ).subscribe();
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    
    return this.options.filter(
      option => option.toLowerCase().indexOf(filterValue) === 0
    );
  }
}

.html :

<mat-form-field class="example-full-width">
        <input type="text"
           placeholder="Pick one"
           aria-label="Number"
           matInput
           [formControl]="myControl"
           [matAutocomplete]="auto">
        <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
            <mat-option *ngIf="isSearching; else notSearching">loader here</mat-option>
            <ng-template #notSearching>
                <mat-option *ngFor="let option of filteredOptions" [value]="option">
                    {{option}}
                </mat-option>
            </ng-template>
        </mat-autocomplete>
    </mat-form-field>

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 adjust the textfield's size proportionally to its parent accordion when the window is resized?

Inside an accordion, I placed a text field with specific widths and heights. However, when I resize the browser window, the accordion width changes proportionally to the window size while the text field width remains the same. This causes the text field to ...

What is the best way to determine if an application has been installed on an Android device while browsing a website?

Let's set the scene: I've got a website that needs to use JavaScript to determine whether my app is already installed on the android device it's currently being used on. If the app is installed, the page will display a link (with a custom ...

Transferring information and storing it in a textbox

I have a homepage that features a popup window. <textarea class="form-control item"></textarea> <button type="button" class="btn btn-primary" name="name">Send</button> Additionally, there is a secondary page at (/conclusion/main) ...

Using async await in node.js allows you to bypass the need for a second await statement when

As I dive into using await async in my Node.js ES6 code... async insertIngot(body, callback) { console.log('*** ItemsRepository.insertIngot'); console.log(body); const data = await this.getItemsTest(); console.log('*** ge ...

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 useState variable is unexpectedly returning an empty array even though I have explicitly set it as an array containing objects

Hey there! I've encountered a scenario with my component where I'm utilizing the useState hook to set up the initial value of myFeeds variable to an array called feeds. I have also implemented an effect that is supposed to update myFeeds with any ...

Transforming the playbackRate property of a web audio-enabled audio element

I recently experimented with integrating an audio element into the web audio API using createMediaElementSource and achieved success. However, I encountered an issue when attempting to change the playback rate of the audio tag. Despite trying multiple appr ...

How come my diary section (5th) is showing up/operating in my teacher's section (4th)?

My journey with HTML, CSS, and Javascript began as a beginner. After following a tutorial on YouTube and making some modifications, everything was running smoothly until the diary section unexpectedly appeared under the teacher's section, which should ...

Exploring React's Capabilities with DOM Manipulation Libraries

When working with React and the OpenSheetMusikDisplay library, I have a situation where I dynamically add elements below a target in the DOM. The target element is a div that I reference using a ref, and everything works smoothly. However, I also need to a ...

The Jquery ajax call encountered an error due to a SyntaxError when trying to parse the JSON data, specifically finding an unexpected character at

I've developed a web application that utilizes just four scripts for dynamic functionality. Overview: Init.php = Database, index.php = webpage, api.php = fetches data from server/posts data to server, drive.js = retrieves information from api.php a ...

What is the most effective way to incorporate the DOMContentloaded event listener into the document using nextJS?

I am working on integrating an HTML code snippet into my Next.js project. The snippet includes an external script with a createButton function. <div id="examplebtn"></div> <script type="text/javascript"> //<![ ...

When attempting to redirect to the home page in Angular 6, the page successfully redirects but fails to load properly

I am new to using angular. Recently, I converted a large project from html/css/php/js to twig/slim, and switched the hosting platform from apache2/sql to s3 buckets/lambda apis. While I have successfully converted smaller projects to angular without any i ...

Understanding type inference in TypeScript

I'm attempting to grasp the concept of inferring generics in Typescript, but I can't seem to figure out where I'm going wrong. Although my concrete example is too large to include here, I've provided a link to a small TypeScript playgro ...

In the node.js application, the route for serving static images from the "/uploads/images" directory using express.static has been found to be dysfunctional

The following Route in my node.js server app API, deployed on the server for fetching images, is not functioning correctly app.use("/uploads/images", express.static(path.join("uploads", "images"))); However, the path below is working perfectly fine app.us ...

The test.ts file does not contain any type definitions

While I am able to successfully utilize my types in .ts files, I am facing difficulties in understanding why it's failing in .test.ts files, even though both files are located in the same folder. Check out the code in the .ts file below: https://i.s ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

Retrieve the data entered in the submit button field

My question concerns a form with two buttons: <form method="post" action=""> <button type="submit" name="age" value="20">Age 20</button> <button type="submit" name="age" value="30">Age 30</button> </form> When ...

Can the state stored in vuex be accessed by nested components?

After reviewing the documentation at: https://vuex.vuejs.org/guide/mutations.html#committing-mutations-in-components and watching the video tutorial here: I'm unsure whether the store is accessible in nested or child components within the parent co ...

Can someone guide me on the process of adding a personalized emoji to my discord bot?

After creating my own discord bot, I'm ready to take the next step and add custom emojis. While tutorials have helped me understand how to use client.cache to type an emoji, I'm unsure of how to upload them and obtain their ID for use in my bot. ...