角度2调节事件或动作的数量在一个控制器上被发射 [英] Angular 2 throttle the amount of event or action gets fired off on a countrol

查看:107
本文介绍了角度2调节事件或动作的数量在一个控制器上被发射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个输入框,我在其中搜索输入的值。我做了它,所以当文本框中的值被更改时它会搜索。
代码是这样的:

In my application I have a inputbox where I search for the inputted value. I made it so it searches when the value inside the textbox has been changed. The code is something like this:

<input id="searchTextField" [(ngModel)]="searchText" (ngModelChange)="SearchTextChange()" />

后端打字稿代码如下:

private SearchTextChange(): void {
//do search 
}

问题在于我意识到这是非常低效的,因为我在大多数情况下意识到,当人们输入一个单词时,我不希望它在人们键入字母a或app,当想要的词可能是苹果或类似的东西。
有没有办法限制在角度2或打字稿中触发的搜索量?
所以我要么每2秒执行一次搜索最大值,要么只让角度在同一个控件上触发最大1 ngModelChange每2秒?

Problem is that I realized this is highly inefficient, because I realized in most cases, when people type a word, I don't want it to search when people type the letter"a" or "app" when the intended word maybe "apple" or something like that. Is there a way to limit the search amount gets triggered either in angular 2 or typescript? so I either only perform a search max every 2 seconds, or only let angular fire off the event on the same control maximum 1 ngModelChange for every 2 seconds?

推荐答案

模板:

<input id="searchTextField" [(ngModel)]="searchText" />

将此代码放入您的组件中:

Put this code in your component :

searchText:string;

ngAfterViewInit()
{
    let inputElm = document.getElementById("searchTextField");
    Observable.fromEvent(inputElm , 'keyup').debounceTime(200).subscribe( res => {
        // this will wait for 200ms and then this will called on input
        // call you api here like
        // this.get(searchText).subscribe();
    });
}

这篇关于角度2调节事件或动作的数量在一个控制器上被发射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆