Do not trigger subscription after debounce time in Angular

I would like the input data to be emitted after 300 milliseconds using debounceTime in Angular:

subject: Subject<any> = new Subject();

constructor(private formBuilder: FormBuilder) { }

ngOnInit();

sendValue(): void {
 this.subject.pipe(debounceTime(300))
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.value);
  })
}

This is the HTML code snippet:

  <input
     (change)="sendValue()"
     required
     [formControlName]="controls.controlName"
     matInput
  />

However, the subscribe method does not execute after 300 milliseconds.

What could be the issue? How do I go about resolving it?

Answer №1

  • Consider using (input) rather than (change). Want to know why? Read more here
  • To ensure continuous streaming and receive new data in .subscribe(), remember to call .next() on Subject

HTML

<form [formGroup]="fg">
  <input type="text" formControlName="firstname" (input)="sendValue()">
  <input type="text" formControlName="lastname" (input)="sendValue()">
</form>

TS

export class AppComponent implements OnInit {
  fg: FormGroup;
  inputSubject = new Subject();

  constructor(
    private fb: FormBuilder,
  ) {}

  public ngOnInit() {
    this.fg = this.fb.group({
      firstname: '',
      lastname: '',
    });

    this.inputSubject
      .pipe(
        debounceTime(300),
      )
      .subscribe(
        () => console.log(this.fg.value)
      );
  }

  public sendValue() {
    this.inputSubject.next();
  }
}

See it in action on stackblitz

Answer №2

When setting up a RxJS Subject observable and subscribing directly, it's important to note that unless a value is pushed into it, nothing will be emitted. Therefore, using an external observable in this scenario may not be necessary.

An alternative approach would involve utilizing the valueChanges observable of the FormControl. By leveraging the valueChanges, there is no need for binding to the change event as well since any change in the element's value will trigger emission due to its association with a FormControl.

To implement this method:

Control

ngOnInit() {
  ...
  this.controls.controlName.valueChanges.pipe(          // <-- form control here
    debounceTime(300)
  )
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.value);
  });
}

Template

<input
   required
   [formControlName]="controls.controlName"
   matInput
/>

Update: merging multiple observables

In cases where there are multiple controls involved, one effective approach is combining all the valueChanges observables using RxJS merge function.

ngOnInit() {
  ...
  merge(
    this.controls.controlName.valueChanges,  
    this.controls.controlPhone.valueChanges,  
    this.controls.controlId.valueChanges,
    ...  
  ).pipe(
    debounceTime(300)
  )
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.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

Using jQuery to send arrays to PHP with $.getJSON

My script includes javascript code to pass an array to PHP like so: var mapIDArray = ["4f8d7684791635ec2e000000", "4f8cbc087916359181000000"]; $.getJSON("rebound.php", { 'mapIDs[]' : mapIDArray ...

Add a jQuery script to the admin panel of a custom WordPress plugin for sending emails through ajax

I've been working on integrating a form into an admin page on WordPress. The goal is to allow users to input their email address and trigger an email to be sent to that address. To achieve this, I'm utilizing a jQuery Ajax function to transmit th ...

What is the process for appending an attribute to a DOM element?

Is there a way to conditionally add the multiple attribute to this element? <mat-select [formControlName]="field.name" multiple> I attempted to do so with the following: <mat-select [formControlName]="field.name" [attr.multiple]="field?.mu ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

What techniques does Angular2 use to handle dependency injection?

When working with Angular2 components, I know that to inject a dependency, you simply annotate an argument in the constructor, like how ThingService is injected here. However, what I am wondering is how Angular actually knows what to inject at runtime. A ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

Tips for updating the bottom color of Material-UI TextField without relying on the <MuiThemeProvider> component

I am facing an issue with a Material UI TextField component that is placed on a dark background. I need to change the text and line colors to red for only this particular instance, while leaving the rest of the TextFields unaffected. My project utilizes @ ...

Having trouble with a malfunctioning part of the API in my NodeJS code. Any suggestions on how to resolve the issue

I'm currently working on developing a REST API in NodeJS for an online store. Here's a snippet of my code for handling POST requests: router.post('/', (req, res, next) => { const order = new Order({ _id: new mongoose.Typ ...

The error message 'this.props.navigation is not defined when using createStackNavigator'

Interested in creating a straightforward navigation example in ReactNative. Take a look at the code snippet below; import React, { Component } from 'react'; import { Button, View, Text } from 'react-native'; import { createStackNaviga ...

Enumeration in zod validation

Currently, I am using a schema in zod and have an object. const escortTypeOptions = [ { value: "Nutrition", label: "תזונה" }, { value: "Training", label: "אימונים" }, { value: "Nutrition ...

Implement a responsive form onto designated webpages with the help of Greasemonkey and JQuery

How can I create a script to generate a text form on the main page of a forum, instead of spawning a new window when clicking the reply button? Here is the source code for the pages where I want to implement this script: Main Discussion Page Reply Page B ...

JavaScript treats string as a primitive value

When it comes to JavaScript, a String is considered a primitive value. However, it can also be treated as a String object. In programming terms, a primitive value refers to a value assigned directly to a variable. This raises the question: var d = "foo"; ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

Utilizing AJAX and JavaScript to generate a table using the AJAX response and placing it within a <div> element

I am currently passing the response of this action in text form, but I would like to display it in a table format. Is there a way to do this? function loadAditivos(){ $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaior ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

What is the process for extracting HTML content using the JavaScript executor?

import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class WebDriverExample { public static void main(String[] args) { System.setProperty("webdriver.c ...

dynamically load react icons

Is there a way to dynamically import an icon based on props received in a component and return a compatible icon? Here is the code in question: import { useEffect, useState } from 'react'; export default function Icon({ libraryName, iconName }) ...

Run PHP code using JavaScript

I am currently using Windows and attempting to use JavaScript/PHP to call a specific form that is saved in a different location. The file D:\Test\Form.php has the following content: <form action="D:\Test\submit.php" method="post"&g ...

Issues encountered when trying to modify the Content-Type of POST requests using ngResource versions 1.0.6 and 1.1.4

Despite numerous attempts and trying various solutions found online, I am still unable to solve this issue. Similar questions have been asked in the following places: How to specify headers parameter for custom Angular $resource action How can I post da ...

Optimizing event mapping with the jQuery "on" function

CODE I: $searchBoxParent.on({ mouseover: function() { $this = $(this); $this.parent().find(".hlight").removeClass('hlight'); $this.addClass("hlight"); }, mouseout: function() { $this = $(this); ...