【问题标题】:How to SetTimeout KeyUp in Angular 7如何在 Angular 7 中设置超时 KeyUp
【发布时间】:2019-06-25 18:48:45
【问题描述】:

我在 Google 中搜索过解决方案,但没有找到。

尝试 1:

<input type="text" #txtSearch (keyup)="onKeyUp(txtSearch.value)">

还有search.component.ts

onKeyUp(val){
    setTimeout(function(){
        console.log(val);
    },500);
}

试过 2

我在这里使用类似的 How to achieve a debounce service on input keyup event in angular2 with rxjs 但在 Angular 7 中不起作用。

终于

我预计 keyup 延迟 0.5 秒,然后是 console.log(value);

【问题讨论】:

标签: angular settimeout delay angular7


【解决方案1】:

对于这种情况,您最好使用debounceTime from rxJs。甚至对角度有更好的支持。看看下面的例子 -

import { Component } from '@angular/core';
import { of, timer, Subject } from 'rxjs';
import { debounce, debounceTime } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  model: string;
  modelChanged: Subject<string> = new Subject<string>();

    constructor() {
        this.modelChanged.pipe(
            debounceTime(500))
            .subscribe(model => {
              console.log(model);
            });
    }

    changed(text: string) {
        this.modelChanged.next(text);
    }
}

<input [ngModel]='model' (ngModelChange)='changed($event)' />

Working Example

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2012-11-11
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多