Lon*_*yễn 2 delay settimeout angular angular7
我在谷歌搜索了解决方案,但没有找到。
尝试 1:
<input type="text" #txtSearch (keyup)="onKeyUp(txtSearch.value)">
Run Code Online (Sandbox Code Playgroud)
和 search.component.ts
onKeyUp(val){
setTimeout(function(){
console.log(val);
},500);
}
Run Code Online (Sandbox Code Playgroud)
试过 2
我在这里使用类似的如何在 angular2 中使用 rxjs 实现输入 keyup 事件的去抖动服务,但在 Angular 7 中不起作用。
最后
我希望 keyup 延迟 0.5s 然后 console.log(value);
对于这种情况,您可以更好地使用debounceTimefrom 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)' />
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8216 次 |
| 最近记录: |