Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user starts typing using the following code snippet:

     ngOnChanges(searchValue: string) {
    if (!this.searchChangeObserver) {
      Observable.create(observer => {
        this.searchChangeObserver = observer;
      }).debounceTime(3000) 
        .subscribe((data) => {
          if (data) {
            typingStuff();
          }
          else {
            notTypingStuff();
          }
        });
      this.searchChangeObserver.next(searchValue);
    }
  }
}

Now, I need to find a way to detect when the user stops typing so that I can execute the notTypingStuff() function.

Is there a simpler method to achieve this?

EDIT

In addition to the above code snippet, I am also utilizing the following code:

constructor(){
    this.modelChanged
      .debounceTime(300)
      .subscribe((data) => {
        if (data) {
          typingStuff();
        }
        else {
          notTypingStuff();
        }
      });
}

However, I still need to determine when the user stops typing for 3 seconds to trigger the notTypingStuff() function as well.

Answer №1

To avoid executing code while typing, you can set up an observable that triggers on input events with a debounce time:

HTML:

<input #yourElement [(ngModel)]="yourVar"/>

Component:

@ViewChild('yourElement') yourElement: ElementRef;

ngAfterViewInit() {
    Observable.fromEvent(this.yourElement.nativeElement, 'input')
        .map((event: Event) => (<HTMLInputElement>event.target).value)
        .debounceTime(3000)
        .distinctUntilChanged()
        .subscribe(data => notTypingStuff());
}

This setup ensures that the method is only called after 3000ms of inactivity following a modification in the input field, essentially when the user stops typing.

EDIT: Angular 9 w/ RxJS 6.5.4

ngAfterViewInit(): void {
    fromEvent(this.yourElement.nativeElement, 'input')
      .pipe(map((event: Event) => (event.target as HTMLInputElement).value))
      .pipe(debounceTime(3000))
      .pipe(distinctUntilChanged())
      .subscribe(data => notTypingStuff());
  }

Answer №2

Angular 6 is the version.

The HTML code snippet:

<input matInput type="text" (keyup)="searchInterest()" [(ngModel)]="keyword" [matAutocomplete]="auto">

This is the component:

public searchInterest() {
    let wordSearch = this.keyword;
    setTimeout(() => {
        if (wordSearch == this.keyword) {
            if (this.keyword) {
                //function that will return your list of objects
            }else{
                //implement code here
            }
        }
    }, 2000);
}

Answer №3

Whenever a user types in the element, I will capture the (keyup) event and verify if the time elapsed since the event was triggered is equal to or greater than 3 seconds.

Answer №4

I believe this approach could also be effective.

SCRIPT.ts

doSomething: any = null;
isActive: boolean = false;

trackActivity(event){

    this.isActive = true;

    clearTimeout(this.doSomething);

    this.doSomething = setTimeout( () => {
        this.isActive = false;
    }, 3000);

}

SCRIPT.HTML

<input (keyup)="trackActivity($event)">

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

Is there a method to obtain the compiled CSS for an Angular 2+ component?

Is it possible to retrieve compiled CSS (as a string) from an Angular2+ component? @Component({ selector: 'test-graph', templateUrl: './test-graph.component.html', styleUrls: ['./test-graph.component.scss'] }) export cla ...

Incorporate playerVars options into your Angular application with the help of @angular/youtube-player package

I am currently using the @angular/youtube-player to display a video within my Angular application. I want the video to play automatically upon loading. After reviewing the documentation, I found the necessary parameters to enable autoplay, but for some re ...

Nestjs: Step-by-step guide to removing a specific application from a Nestjs monorepo using nest/cli

Is there a method to delete a specific app within a nestjs monorepo using the nest/cli? I have searched through the documentation and developer forums but cannot seem to find a solution. ...

Having trouble updating npm using npm install npm@latest -g and encountering an error?

Encountering errors and warnings while updating npm to the latest version c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External>npm cache clean --force npm WARN u ...

What could be causing the issue of console.log() being called multiple times in Angular when invoking a method through text interpolation?

Utilizing Text interpolation to invoke a method. home.component.html <p>{{myMethod()}}</p> home.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: './h ...

"Trouble with Angular reactive form submission - selected options not being passed through

I have a form that is dynamically populated with multiple select inputs: <form [formGroup]="searchForm" (ngSubmit)="onSubmit(searchForm.value)"> <div class="col-md-2" *ngFor="let filter of this.filters; index as i"> <div class="for ...

Guide on transferring information obtained from a service to an Angular datatable

Recently, I started working on Angular 4 and encountered an issue while trying to display data from an Angular service in JSON format using angular-datatable. Despite trying various options, I am unable to get the data to display within the columns of the ...

Simplifying imports in Angular, the easy way: A guide to stream

We recently made a change to our Angular project by moving the npm-library @ng-plus/modal to live as a project library under the project/ngplus-modal folder. One issue we encountered is with the imports within the project. Even though we previously def ...

What could be causing my Angular 8 project to fail to start following the installation of Angular 10 CLI?

Previously, I was working on an Angular 8 project on my computer. However, I now need to install Angular 10 to run another project. To do so, I globally installed the new version with the following command: npm install -g @angular/cli After successfully ...

Combining Closure Compiler with Typescript

My objective is to leverage Typescript along with Closure Compile (advanced compilation) to target ES5 and then minify the resulting output. Is it mandatory for me to replace tsc with tsickle? I find that tsickle does not provide support for all options a ...

Guide to adding a custom font to your Angular 5 project

I am looking to integrate a new font into my Angular 5 project. So far, I have attempted: 1) Moving the file to assets/fonts/ 2) Including it in the styles section of .angular-cli.json However, it seems that the file is not a regular .css file; it is a ...

Utilizing images in a compiler run with the option of `allowJS:true` is key

Looking to develop a React Native library using JavaScript instead of typescript, but want to leverage TSC for its ability to generate type declarations from jsdoc comments. However, encountering an issue where local images are not included when the ts com ...

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

Angular2 recursive template navigation

Is it possible to create a recursive template in Angular 2 without using ng-include? It's puzzling why this feature seems to be missing in Angular 2... HTML: <div ng-app="app" ng-controller='AppCtrl'> <script type="text/ng-templat ...

The parameters provided in TypeScript do not align with any signature of the call target

In JavaScript, a function can be called with any number of parameters. If a parameter is not passed, it will default to undefined without causing an error. Below is a code snippet for reference: function test(a,b){ if(b){console.log(b)} else{console ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

Ways to conceal a fabric button

Is there a way to hide my Material button properly? The button appears grey and works fine: <button mat-raised-button class="mat-primary" (click)="deleteClick()" [disabled]="data.createMode"> <mat-icon>delete_forever</mat-icon>DELET ...

Typescript Error:TS2345: The argument '{ theme: string; jsonFile: string; output: string; }; }' is not compatible with the parameter type 'Options'

Encountering an error mentioned in the title while using the code snippet below: import * as fs from 'fs' import { mkdirp } from 'mkdirp' import * as report from 'cucumber-html-reporter' const Cucumber = require('cucumber ...

Encountering a hitch in loading Typescript modules

I'm attempting to utilize Typescript modules, but I'm encountering issues with loading them properly. Each time I try to import the module, I receive the following error message in my JS file: JavaScript runtime error: 'exports' is und ...

Tips for integrating an angular module that lacks Universal compatibility into an angular/cli application with server-side rendering (SSR) support

Greetings everyone! I've been working on developing an Angular app that utilizes Universal with SSR for quite some time now. At times, while including a module like ngx-editor, I noticed that the server would fail silently without any indication of wh ...