My goal is to implement an Angular Material Autocomplete feature that only triggers after the user has inputted at least three characters. Currently, I have it set up so that every click in the input field prompts an API call and fetches all the data, which is not ideal.
What I envision and aim to achieve is for the API call to be triggered only when the user has typed in a minimum of three characters, and for the autocomplete options to display only the matching results in the mat-option element.
If my explanation isn't clear enough, please let me know in the comments below.
Below you can find the code snippets:
dashboard.component.html:<form [formGroup]="dasboardSearchForm" class="dashboardSearch">
<div class="form-fields">
<mat-form-field class="dashboard-search">
<mat-label>Search users...</mat-label>
<input type="text" matInput [formControl]="myControl" placeholder="search users..." [matAutocomplete]="auto" (change)="onSelected($event)">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
<mat-option *ngFor="let option of filteredOptions | async" [value]="option" routerLink="/customers/customers/{{option.id}}">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
</form>
dashboard.component.ts:
onSelected(event: any) {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
switchMap(value => this._filter(value))
);
console.log('onSelected: ', this.filteredOptions);
}
displayFn(user: AutocompleteCustomers): string {
return user && user.name ? user.name : '';
}
private _filter(value: string) {
const filterValue = value.toLowerCase();
return this.dashboardService.getCustomers().pipe(
filter(data => !!data),
map((data) => {
debounceTime(3000); // Placeholder for potential error?
console.log(data);
return data.filter(option => option.name.toLowerCase().includes(filterValue));
})
)
}
dashboard.service.ts:
getCustomers(): Observable<AutocompleteCustomers[]> {
return this.httpClient.get<AutocompleteCustomers[]>(`${environment.apiUrl}data/customers`);
}
And here is the model interface for Observables:
export interface AutocompleteCustomers {
id: string;
name: string;
}