Is it possible to delay the execution of the onkeypress event by one second in order to prevent it from triggering a method multiple times consecutively?

Currently, I am developing a program that utilizes a method to display data in a table using a textbox. The issue is that the program is being called more than 10 times with each execution. Is there any way to prevent this from happening?

The textbox element is displayed below:

<input #input matInput placeholder="Search data" (keyup)="onKeypressEvent($event)">

Below is the method being invoked:

  onKeypressEvent(event: any){
    fromEvent(this.input.nativeElement,'keyup')
        .pipe(
            debounceTime(150),
            distinctUntilChanged(),
            tap(() => {
                this.paginator.pageIndex = 0;
                this.loadData();
            })
        )
        .subscribe();
  }

Answer №1

The reason for this issue is that a new chain is created with every key press, rendering debounceTime() ineffective. To address this, it's recommended to create a Subject and push key presses into it. Then, establish just one subscription either in the constructor or within onInit():

keyPress$ = new Subject();

...

keyPress$.pipe(
  debounceTime(150),
  distinctUntilChanged(),
  tap(() => {
    this.paginator.pageIndex = 0;
    this.loadData();
  }),
).subscribe();

...

onKeypressEvent(event: any) {
  this.keyPress$.next(event);
});

Answer №2

Your current code appears to be utilizing @viewChild().

Here is a simple and functional alternative that eliminates the need for an extra Subject.

ngAfterViewInit() {
    fromEvent(this.input.nativeElement, "keyup")
      .pipe(debounceTime(1000)) // Adjust debounceTime as needed
      .subscribe((val: KeyboardEvent) => {
        console.log(this.input.nativeElement.value);
      });
  }

Remember to unsubscribe in the onDestroy method.

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

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

Error in Angular 5: Google Maps not defined

Having trouble implementing Google Maps on my Angular 5 app. Upon loading the view, I am encountering this error in the JavaScript console: LoginComponent_Host.ngfactory.js? [sm]:1 ERROR ReferenceError: google is not defined at LoginComponent.ngAfterVie ...

Ways to customize the size of the material select dropdown to distinguish it from the form field width

Is there a way to customize the width of a <mat-select> from the @angular/material library so that the form field displays in a small width (75px) while the drop down menu can expand for longer text options? My goal is to achieve a layout similar to ...

Avoid triggering the onClick event on specific elements in React by utilizing event delegation or conditional rendering

programming environment react.js typescript next.js How can I prevent the onClick process from being triggered when the span tag is pressed? What is the best approach? return ( <div className="padding-16 flex gap-5 flex-container" ...

Dockerized Angular CLI app experiencing issues with hot reload functionality

My existing angular cli application has been dockerized with the following setup: Dockerfile at root level: # Create a new image from the base nodejs 7 image. FROM node:7 # Create the target directory in the imahge RUN mkdir -p /usr/src/app # Set the cr ...

I'm struggling to grasp the utilization of generics within the http.d.ts module in Node.js code

type RequestHandler< Request extends **typeof IncomingMessage = typeof IncomingMessage**, Response extends **typeof ServerResponse = typeof ServerResponse**, > = (req: InstanceType<Request>, res: InstanceType<Response> ...

Tips for extracting value from a dynamic element in Angular 2

Here is the HTML code: <tr *ngFor="let item of items"> <td #id>{{item.id}}</td> <td>{{item.comment}}</td> <td> <i class="fa fa-trash-o" aria-hidden="true" (click)="deleteTime(id.value)"> ...

TypeScript is unable to detect the .sequelizerc configuration file

I have a file called .sequelizerc which contains the following configuration: const path = require('path'); module.exports = { config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'), 'migrations-path': ...

Connect a datetime-local typed input to a Date attribute in Angular 2

Can a property of type Date in a component be bound to an HTML5 input with the type attribute set as datetime-local? For example, I have a component with the following property: public filterDateFrom: Date; And in my template, I am trying to bind this p ...

A guide to building a versatile component using Ionic 3 and Angular 4

I decided to implement a reusable header for my app. Here's how I went about it: First, I created the component (app-header): app-header.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-header', te ...

What is the best way to inject a custom Angular service into a test in TypeScript without needing to mock it?

I have defined my modules and tests as shown below, but I encounter an issue when attempting to inject ContentBlocksService into the beforeEach(mock.inject((ContentBlocksService)... statement. It shows an error message saying Unknown provider ContentBlocks ...

Vue 4 and TypeScript: Dealing with the error message 'No overload matches this call'

In my Vue-Router 4 setup, I am trying to combine multiple file.ts files with the main vue-router (index.ts) using TypeScript. However, it throws an error that says "TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): ne ...

An Angular module downloaded from npm seems to be lacking the required @NgModule declaration

There seems to be a missing @NgModule and @Directive declarations in an NPM module, even though they exist in the source code on Github. This is causing an issue with importing a directive for databinding from an HTML attribute. I am attempting to utilize ...

Error encountered in Angular2: Attempted to access property 'compilerOptions' which is undefined

I encountered a TypeError: Unable to access the 'compilerOptions' property of undefined Below is the snippet of my compilerOptions code: { "compilerOptions": { "target": "ES5", "module": "commonjs", "emitDecoratorMetadata": tr ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

Display or conceal password text with Nativescript

I am working on a login form where I need to toggle the visibility of the password text. Below is the code snippet that I have implemented. Here is the code I tried: <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff"> ...

Is it feasible to restrict generic classes for particular functions?

Imagine creating a customized container in TypeScript. Let's consider this straightforward example: class Container<T> { val: T; constructor(t: T) { this.val = t; } } Now, let's say you want to implement a function that can gene ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Error in Angular 2: Trying to access a property that is undefined - 'Symbol(Symbol.iterator)'

It appears that the error I am encountering is related to how I handle data when returning it. I have been unable to pinpoint where my return statement may be missing or if that is even the root cause of the issue... The error occurs when deleting somethin ...