The Keyup Filter in the FromEvent function is malfunctioning and not behaving as anticipated

I have created a simple search function for my app using the FromEvent KeyUp and debounceTime features as shown in the code below:

<input matInput #inputSearch>

@ViewChild('inputSearch', { static: false }) input: ElementRef;

fromEvent(this.input.nativeElement, 'keyup')
      .pipe(
        filter((val: any) => val.target.value.length > 3),
        debounceTime(500),
        distinctUntilChanged(),
        switchMap((val: any) => this.userService.get(val.target.value))
      )
      .subscribe(data => {
        console.log(data);
      });

Although the search function is triggered when something is typed in the input box, the filter I applied to only execute the API call when the input value is greater than 3 does not seem to be working properly.

I am currently stuck on this issue. Any suggestions? Thank you!

Answer №1

Avoid using fromEvent and keyup. Instead, consider utilizing a more convenient method recommended by Angular. You can utilize Angular Forms and valueChanges as shown below to achieve your desired outcome.

HTML

<div [formGroup]="myGroup">
  <input formControlName="search" type="text" placeholder="search">
</div>

Define your FormGroup in the Component as follows.

myGroup: FormGroup;

this.myGroup = new FormGroup({
   search: new FormControl()
});

You can then subscribe to the value changes of the search FormControl like this.

this.myGroup.get('search').valueChanges.debounceTime(500)
  .subscribe((val: any) => {

    const search = val.trim();
    if (search.length > 3) {
      console.log('Search Term => ', search);
      // TODO: Handle your API Call Here.
    }
});

Check out a functional StackBlitz demo here.

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

Display a loading progress bar with jQuery AJAX as your single page website content loads

I am currently working on a simple web page layout that consists of a navigation bar at the top and a body wrapper. Whenever a user clicks on a link in the navigation bar, I use .load to load the content of the page into the wrapper div. $(this).ajaxStar ...

What is causing JS to malfunction and preventing App Scripts from running `doGet()` when using either `e` or `event` as parameters?

Following a Basic Web App video last night, I meticulously followed every step until the very end where things started to go wrong. Today, I decided to start from scratch and recreate it all. Despite weeks of coding practice, I can't seem to figure ou ...

Struggling to retrieve service information for implementation in the component

I am currently working on a project where: 1. I have created a news.service.ts service file with the following code: 2. Within the service, I have implemented a function named throwData() that returns the service data. Here is the code snippet: im ...

Ionic 4 Tabs with Smooth Scrolling

I recently started using Ionic 4 and I'm trying to create scrollable tabs in Ionic 4. However, when I include multiple tabs as shown in the code below, they become compressed and appear within the same viewing space. <ion-tab-bar slot="top"> ...

What is the best way to differentiate between two calls to the same method that are based on different arguments?

Currently, I am utilizing sinon to mock functions from Google Drive in my NodeJS project. In a single test scenario, I make two separate calls to the create method (without the ability to restore between calls): // Call 1: drive.files.create({ 'reques ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

Attempting to activate template rendering with Meteor session

I'm currently facing an issue with Meteor sessions and how my code is triggering the rendering of a template. At the moment, I have a session that sets its ._id to whatever is clicked. Template.sidebar.events({ /* on click of current sidecat class ch ...

Comparing jQuery's min-width and width properties: A guide on eliminating pixels

Exploring some basic jQuery and JavaScript here. When I use the .width() method, I get an integer value. However, when I use .css('min-width'), it returns a value in pixels which makes it challenging to perform calculations. What would be the be ...

Issue with Type-Error when accessing theme using StyledComponents and TypeScript in Material-UI(React)

I attempted to access the theme within one of my styled components like this: const ToolbarPlaceholder = styled('div')((theme: any) => ({ minHeight: theme.mixins.toolbar.minHeight, })); This information was found in the documentation: htt ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

The Framework of Storing Data in Angular 2

Embarking on a new project for a corporate client, I find myself in the initial stages of making fundamental architectural decisions. While my background lies with .NET applications, WPF and Flash, this new venture requires web delivery, leading me to cons ...

Some browsers are experiencing issues with Javascript functionality

My JavaScript code is functioning perfectly on my development machine in Chrome, Firefox, and Safari. However, when others test it on their browsers, the value update does not work at all. Can anyone suggest how I can replicate this issue locally? Browser ...

node-ts displays an error message stating, "Unable to locate the name '__DEV__' (TS2304)."

I recently inserted __DEBUG__ into a TypeScript file within my NodeJS project. Interestingly, in VSCode, no error is displayed. However, upon running the project, I encounter an immediate error: error TS2304: Cannot find name '__DEBUG__'. I att ...

What are the reasons for a jQuery function to run in a selective manner?

There seems to be some inconsistency in the behavior of this incomplete script that I'm trying to debug. The issue arises when I click off an item, as sometimes the $(editObj).removeAttr('style'); line of code executes and other times it doe ...

How to achieve dynamic class instantiation through constructor injection in Angular 8?

Despite my efforts to find a solution, my understanding of Dependency Injection in services is still limited, making it challenging to get this thing working. I'm left wondering if there's any way to make it work at all. My current setup involve ...

"Customizing text input colors in Angular Material: A step-by-step guide

Welcome to my User Form: https://i.stack.imgur.com/7eLp9.jpg I'm facing an issue where the color of the input field is white, blending with the background color. I've been searching for how to change the color of the input field without any luc ...