Here's the less painful way of debouncing keystrokes if you don't want to use the formcontrol
approach.
search.component.html
<input type="text" placeholder="Enter a value" name="foo" [(ngModel)]="txtQuery" (ngModelChange)="onFieldChange($event)">
search.component.ts
export class SearchComponent {
txtQuery: string; // bind this to input with ngModel
txtQueryChanged: Subject<string> = new Subject<string>();
constructor() {
this.txtQueryChanged
.debounceTime(1000) // wait 1 sec after the last event before emitting last event
.distinctUntilChanged() // only emit if value is different from previous value
.subscribe(model => {
this.txtQuery = model;
// Call your function which calls API or do anything you would like do after a lag of 1 sec
this.getDataFromAPI(this.txtQuery);
});
}
onFieldChange(query:string){
this.txtQueryChanged.next(query);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…