0

How to hold event triggering in angular.

This question related with my another question : how to stop array.filter() function

I have tried those all answers. But am not satisfied with that answers.

So I did something from my own idea.

Problem: I have a ngmodelchange event and that is for calling a method. You can see my latest question for why am using ngModelChange() event. Anyway I will explain here also.

Am search and filtering large amount of data using ngModelChange event. So the problem is when I typing character's continuously the application is hanging.

My Suggestion

So I have suggested myself for use some logic to call the filter function after user has stop the typing. But we don't know when the user will stop typing.

So I create a logic below.

What am Did

(ngModelChange)="clearSearch(gloablFilterValue)"// html side

In .ts side

 clearSearch(newValue: string) {
       this.oldFilterText = newValue;
        if (this.isLooping) {
            return false;
        }  

        for (let i = 0; i > newValue.length + 1; i++) {
            this.isLooping = true;
            if (this.oldFilterText == newValue) {
                this.splitCustomFilter();//filter function
            }
        }

    }

The above code is not working. am just starting to write logic. So if some have any idea. please come with me you suggestion and ideas to achieve this.

Main question

How can we stop the event triggering until the user has typing values in text box? And how can we start the event triggering the user has typed values in textbox?

**Important: I don't want to use focus out and blur events. because the filter should works while the user typing the values.

Oleksii Pavlenko
  • 1,327
  • 1
  • 11
  • 25
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

1 Answers1

3

What you're looking for is called deboucing. A good alternative is throttling. RxJS supports has both operators, called debounceTime and throttleTime. Here's a quick example of how to utilize them.

In the template, listen for the input event (or some other event, based on what you're listening to in your use-case).

<input type=text (input)="onInput($event.target.value)">

In your component code, create a subject and then use the appropriate operator on it before you subscribe to it.

// create a subject
private subject = new Subject<string>()

// function to call when event fires
public onInput(input: string) { this.subject.next(input) }

ngOnInit() {
  // debounce the stream
  this.subject.debounceTime(300).subscribe(inputText => {
     // this is where you can do you .filter
     console.log(inputText)
  })
}

Of course, you can tweak the 300 parameter as you wish.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91