Using debounceTime and distinctUntilChanged in Angular 6 for efficient data handling

I recently came across a tutorial on RxJS that demonstrated the use of debounce and distinctUntilChanged. I'm trying to implement it in Angular 6, but I'm facing some challenges.

Here is the code from the tutorial:

var observable = Rx.Observable.fromEvent(input,'input');

observable.map(event=>event.target.value)
    .debounceTime(2000)
    .subscribe({
        next:function(value){
        console.log(value)
    }
}

This is my attempt at implementing it:

In the HTML file:

<input class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">

In the TypeScript file:

import { Subject,Observable } from "rxjs";
import { debounceTime,distinctUntilChanged } from "rxjs/operators";

ngOnInit() {
    // initialization
    this.userQuestion = new Observable;
    this.userQuestion.pipe(
        debounceTime(2000)).subscribe(val => {
            console.log(val)
        }
    )
}

However, my implementation does not seem to work correctly. Can anyone provide guidance on how to make it work?

Answer №1

There are two important things to remember:

In your typescript file, make sure you initialize your Observable correctly. To create an Observable based on a DOM event like 'input', use the 'fromEvent' method.

Additionally, remember that pipe is used to chain operators together and should not contain a subscribe function.

UPDATE

If you are using @ViewChild, remember to create the Observable in ngAfterViewInit as ViewChild won't be accessible before that point.

In your template:

<input #questionInput class="form-control" [(ngModel)]="userQuestion" type="text" name="userQuestion" id="userQuestions">

In your .ts file:

@ViewChild('questionInput') questionInput: ElementRef;

public input$: Observable<string>;

////
  ...your code here...
////

ngAfterViewInit() {
   this.input$ = fromEvent(this.questionInput.nativeElement, 'input')
      .pipe(
         debounceTime(2000),
         map((e: KeyboardEvent) => e.target['value'])
      );

     this.input$.subscribe((val: string) => {
         console.log(val)
      });
}

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 improvements can I implement in this React Component to enhance its efficiency?

Seeking advice on improving the efficiency of this React Component. I suspect there is code repetition in the onIncrement function that could be refactored for better optimization. Note that the maxValue prop is optional. ButtonStepper.tsx: // Definition ...

Show the interface value for an array type

I have created a component to display API data. The structure of the component is as follows: HTML: <div *ngFor="let customer of customers"> <p>Name: {{customer?.name}}</p <p>Phone: {{customer?.phoneNumbers}}</p </div&g ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

Retrieving user data from Ngrx store upon page refresh

Is it safe to retrieve user data from the database and store it after refreshing the page? Currently, I am getting the user ID from local storage in Guard and dispatching an action to retrieve the user data. Should I consider a different approach for thi ...

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Displaying time in weekly view on the Angular 4.0 calendar

I've integrated the library into my Angular application to manage calendar events display and creation. The app features a monthly, weekly, and daily view option for users. However, I noticed that in the weekly view, only the dates are shown without ...

Proper management of setTimeout in an Angular application

I am working on a one-page web application where the main component's ngOnInit() function triggers a recursive function called loopDoSomething() using setTimeout: ngOnInit(): void { // Perform some operations this.loopDoSomething(); } loopDoSome ...

The functionality of Angular Material Chip is encountering issues when paired with Angular 7

Issue with Angular Material Chip module compatibility in Angular version 7 Tech: Using Angular version 7, angular cli, and angular material Desired Outcome: Looking to successfully implement the angular material chip module Steps taken so far: Insta ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Wrong method executed when trying to use Angular http put

I am facing an issue with my http.put wrapper where it is calling the incorrect PUT overload. I specifically need the one that returns Observable<Object>, but instead it is calling Observable<ArrayBuffer>. Here is the code snippet for my http.p ...

Utilize/Absolve/Add a Prefix to angular material scss styles

Issue I am facing a challenge with integrating angular material SCSS into my application. I want to ensure that these styles are isolated and scoped specifically for my application, as it will be embedded within a larger monolith. The goal is to prevent a ...

When using Angular, automatically shift focus to the next input field by pressing the

I am faced with a challenge involving multiple editable inputs on my screen. Alongside these editable inputs, there are buttons and disabled inputs present. The current behavior is such that when I press Tab, the focus shifts to the HTML elements between ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...

The toISOString() method is deducting a day from the specified value

One date format in question is as follows: Tue Oct 20 2020 00:00:00 GMT+0100 (Central European Standard Time) After using the method myValue.toISOString();, the resulting date is: 2020-10-19T23:00:00.000Z This output shows a subtraction of one day from ...

SolidJS directives utilizing use:___ result in TypeScript errors when used in JSX

As I work on converting the forms example from JS to TS, I came across a typescript error related to directives in HTML: It appears that validate and formSubmit are being recognized as unused variables by typescript, resulting in the following jsx error: ...