Exploring the implementation of debounce functionality for an array of items in an Angular project

Can someone demonstrate how to implement debounce time in an angular input search for filtering a list of items? Should RXJS be used and if so, how can it be integrated into the filterReports function? Any code samples would be greatly appreciated. Code example below:

protected reports: Array<ReportGroupModel> = [];
protected filteredReports: Array<ReportGroupModel> = [];

constructor(
    protected route: ActivatedRoute,
    protected httpService: HttpService
) {
    super(route);

    this.titleIcon = 'fa-bar-chart';
    this.titleSufixKey = 'reports';

    this.filterReports = debounce(this.filterReports, 500);
}

filterReports(filter: any) {

    const searchText = filter.target.value?.toUpperCase();

    if (searchText) {

        let newFilteredReports: Array<ReportGroupModel> = [];

        for (let reportGroup of this.reports) {
            let foundItems = reportGroup.items.filter(x => x.title.toUpperCase().includes(searchText));

            if (foundItems && foundItems.length > 0) {
                newFilteredReports.push(new ReportGroupModel(reportGroup.header, foundItems));
            }
        }

        this.filteredReports = newFilteredReports;
    }
    else
        this.filteredReports = this.reports;
}

ngOnInit() {
    super.ngOnInit();

    this.filteredReports = this.reports;
}

And here is the corresponding HTML:

<div class="d-flex">
    <input search="text" class="form-control mw-200p ml-auto" (keyup)="component.filterReports($event)" autofocus placeholder="{{ 'search' | translate }}"/>
</div>
<div class="d-flex flex-wrap pl-2">
    <div *ngFor="let report of component?.filteredReports" class="pr-5 pt-2" style="width: 350px;">
        <h3>{{report.header | translate}}</h3>
        <ul class="list-unstyled pl-1">
            <li *ngFor="let item of report.items">
                <i class="fa {{item.icon}} mr-h"></i>
                <a class="link" [routerLink]="item.path"> {{item.title}} </a>
                <p *ngIf="item.description" class="text-muted">{{item.description}}</p>
            </li>
        </ul>
    </div>
</div>

Answer №1

To tackle this issue effortlessly, utilizing the reactive form module is recommended. However, if you prefer to stick with ngModel, here's a workaround you can implement.

searchChanged = new Subject();
protected reports: Array<ReportGroupModel> = [];
protected filteredReports: Array<ReportGroupModel> = [];

Remember to update the subject every time the keyup event occurs.

<div class="d-flex">
    <input search="text" class="form-control mw-200p ml-auto" (keyup)="onKeyUp($event)" autofocus placeholder="{{ 'search' | translate }}"/>
</div>
//.ts
onKeyUp(value: string) {
  this.searchChanged.next(value)
}

Now, leverage the searchChanged subject to debounce the event updates.

constructor(
    protected route: ActivatedRoute,
    protected httpService: HttpService
) {
    ...
    this.searchChanged.pipe(
        debounceTime(300)
    // To ensure proper cleanup, consider adding takeUntil or similar method for unsubscribing from this observable when the component is destroyed.
    ).subscribe(value => {
       this.filterReports(value);
    })
}

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

Can I programmatically retrieve a comprehensive list of all global HTML attributes available?

Exploring the extensive list of global HTML attributes can be overwhelming, especially when considering how it continues to evolve with browser updates. Can JavaScript be leveraged to dynamically generate a complete list of these attributes without the ne ...

What is the best way to select a specific value from JSON (Webhook) Data?

I am looking for a way to extract and store a specific value from a JSON data into a variable. Specifically, I want to save the value of Name (John) in a variable like this: var name = "". I attempted using var name = data.Name but it is not wor ...

Learn how to efficiently send multiple image files to the server by utilizing Formidable and React JS

I am encountering an issue while attempting to upload five images to the server. The code file is provided below, and any assistance would be greatly appreciated. In this scenario, I am inputting image files and storing them in an array, but Formidable in ...

What is the method for obtaining a thumbnail of a Facebook profile picture?

Successfully retrieving album images from profile pictures using the following api call: facebookModule.requestWithGraphPath("/"+albumId+"/photos", { fields : 'source,icon' } [..] My question now is whether there's a method to obtain p ...

The JSON parsing function is experiencing significant slowness issues specifically in Internet Explorer version

While using the json_parse function to parse data from an Ajax call, I've noticed that it works smoothly in FF but not as well in IE7. The process is very slow and at times freezes the browser. Unfortunately, due to certain constraints, I am unable to ...

Typescript: How can we determine the data type of React Router Link?

Trying to pass Link from react-router-dom as props and needing to specify it in the interface. While hovering over the Link element, the type displayed is: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>> ...

Obtaining a variable from HTML and passing it to Node.js

Currently, I am utilizing express to handle form submissions. Within my HTML file, there are 20 inputs with unique ids such as address1, address2, address3, and so on. In my node js code, I access these input values using req.body.address1. Users have th ...

What is the best way to utilize node exec in synchronous mode?

I have a scenario where I need to run exec synchronously. Is there an alternative method to achieve this without using the deprecated execSync library? Can bluebird promises be used for this purpose? for (var i = 0; i < testCasesLength; i++) { va ...

Having issues with my Angular setup on the Restify server - help needed!

I am currently learning how to utilize Restify in order to construct a Restful API and collaborate with Angular. My current project structure is outlined below: Project page_admin core.js index.html node_modules restify mongo ...

An effective and lightweight method for submitting multiple value fields in a form to an ASPX web form

Let me provide a clearer explanation of the question I have: On my aspx webform, I am creating an entity and capturing simple data. This entity can have multiple child entities linked to it in a one-to-many relationship, all created from the same form. I ...

Update the controller variable value when there is a change in the isolate scope directive

When using two-way binding, represented by =, in a directive, it allows passing a controller's value into the directive. But how can one pass a change made in the isolated directive back to the controller? For instance, let's say there is a form ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Creating a project that utilizes Bing Translate and the Node.js programming language

As I work on developing a web application that enables users to translate text using the Bing translator API, I am facing an issue. I attempted to execute a translator.js file via a script tag, but encountered a roadblock since Node.js code cannot be run t ...

Steps for recreating a Jquery Mobile form element with the same name after destroying it

As I delve into Jquery Mobile, I encounter a scenario where I must dynamically generate form fields (select, input, etc) using the following approach: $fieldInput = $('<input type="text" name="' + fieldName + '" />'); Initially, ...

Bug: Experiencing issues with horizontal scrolling exclusively on Chrome mobile

I'm currently working on a website and I'm facing an issue with a horizontal scroll appearing only on the mobile version when using Chrome browser (Firefox works perfectly fine). Despite trying various solutions like adding overflow-x:hidden; to ...

Is C# MVC compatible with Angular?

Is there a way to create a project in Visual Studio 2017 or 2019 from C# MVC with Angular? I've watched tutorials where a template is shown, but it's not appearing for me. Can someone please help? I can't find the template Tutorial I trie ...

Transform a single attribute in an array of objects using angularjs and Javascript to a different value

Within an angularjs controller, the following code is used: var ysshControllers = angular.module('theControllers', []); ysshControllers.controller('CommonController', function($scope, $http, $route) { $scope.dbKey = $route ...

What makes the vue <template> is incorrect when using v-bind:src?

I'm facing a challenge in dynamically switching html content. I tried using vue-loader src to import, but v-bind:src doesn't seem to have any effect. <template src="./app.html"></template> It seems to be working fine here. <temp ...

Angular2 is throwing an error: "NavigationService provider not found! (MenuComponent -> NavigationService)"

I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent at the top that utilizes the NavigationService to navigate throughout different sections of my app. To ensure that the NavigationService remains a singleton, I ...

Filtering nested arrays in Javascript involves iterating through each nested

I have a nested array inside an array of objects in my Angular app that I'm attempting to filter. Here is a snippet of the component code: var teams = [ { name: 'Team1', members: [{ name: 'm1' }, { name: 'm2' }, { name ...