I have an input field where a user can search different user in my app. But I want to make a search in such a way that when the user types in the input it should simultaneously search. I have implemented my fuction which calls my back-end but i just want to know how can i send the value of input field with every keystroke. Please help
3 Answers
You should handle the ngModelChange Angular event (see this stackblitz). It takes into account any kind of change in the input field (key strokes, cut/paste with context menu, etc.), and ignores key strokes that do not result in an actual change (e.g. pressing and releasing Shift by itself does not trigger ngModelChange).
<input [ngModel]="searchStr" (ngModelChange)="modelChange($event)" />
import { Component } from "@angular/core";
import { FormsModule } from "@angular/forms";
@Component({
})
export class AppComponent {
public searchStr: string = "";
public modelChange(str: string): void {
this.searchStr = str;
// Add code for searching here
}
}
Comments
I would use a form control to expose the valueChanges observable. This observable emits every time the value of the form control changes.
<input [formControl]="search">
This allows you to control the flow of the typeahead search
// component.ts
ngOnInit(){
this.search.valueChanges
.pipe(
// debounce input for 400 milliseconds
debounceTime(400),
// only emit if emission is different from previous emission
distinctUntilChanged(),
// switch map api call. This will cause previous api call to be ignored if it is still running when new emission comes along
switchMap(res => this.getSearchData(res))
)
.subscribe(res => {
this.result = res;
})
}
With this, you are controlling how often the api call gets called (debounceTime & distinctUntilChanged) and ensuring the order of which the api calls finish (switchMap). Here is a stack blitz demoing this.