Skip to content

Instantly share code, notes, and snippets.

@greenygh0st
Last active July 23, 2020 23:21
Show Gist options
  • Save greenygh0st/5f0f7ea271e06a87bc45688eb498f25b to your computer and use it in GitHub Desktop.
Save greenygh0st/5f0f7ea271e06a87bc45688eb498f25b to your computer and use it in GitHub Desktop.
Debounce search fields in Angular
// In HTML component
// <input placeholder="Search" ... (keyup)="onSearchKeyUp()" [(ngModel)]="searchFilter" />
// in .ts file
searchFilter: string;
private searchSubject: Subject<string> = new Subject();
private searchSubscription: Subscription;
filterItems() {
// do the thing by searchFilter
}
onSearchKeyUp(){
this.searchSubject.next();
}
ngOnInit() {
// setup the filter debounce
this.searchSubscription = this.searchSubject.pipe(
debounceTime(500)
).subscribe(() => {
this.filterItems();
});
}
ngOnDestroy() {
// prevent memory leaks
if (this.searchSubscription)
{
this.searchSubscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment