I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete dropdown. Everything seems to be working fine, however, after loading the last request from the service, I noticed that I need to perform an action (such as clicking or typing) in order to view the last result from the response in the autocomplete dropdown. Interestingly, when I tested this on a new Angular project, I did not encounter this issue. Just for reference, my Angular version is 10.
The code snippet responsible for loading the data is as follows:
// Search a place
search = new FormControl();
body: any;
isLoading: boolean;
errorMsg: string;
filteredPlace: any;
places = [];
minLengthTerm = 2;
selectedValue = '';
@ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;
this.search!.valueChanges.pipe(
distinctUntilChanged(),
debounceTime(500),
tap(() => {
this.places = [];
}),
filter(value => value ? true : false),
switchMap(search =>
this.placeService.searchPlace(search).pipe(catchError(() => of([])))
)
).subscribe((val) => {
this.places = val;
console.log(val);
if (this.places.length === 0) {
// If no result we show the possibility to create a place
console.log(('No Data'));
this.autocomplete.closePanel();
}
})
onSelResult(option: any){
this.selectedValue = option.name;
console.log(option);
}
clearSelection() {
this.selectedValue = '';
this.places = [];
}
The corresponding HTML code:
<mat-form-field appearance="fill">
<mat-label>Rechercher un lieu</mat-label>
<input
matInput
placeholder="Type de lieu, nom, adresse, département, code postal, ville"
[formControl]="search"
[matAutocomplete]="auto"
[value]="selectedValue">
<button
matSuffix mat-icon-button
aria-label="Clear" (click)="clearSelection()">
<mat-icon>close</mat-icon>
</button>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let place of places" (onSelectionChange)="onSelResult(place)">
<span><b>{{place.name}}</b> ({{place.zipCode}})</span>
</mat-option>
</mat-autocomplete>
<mat-hint>
Vous pouvez séparer par des virgules pour lancer la recherche sur plusieurs champs. <b>Exemple : Cimetière, 95</b>
</mat-hint>
</mat-form-field>
I'm puzzled as to why an action is needed to view the latest result of my request (an array of objects) in the autocomplete dropdown.
I attempted to fetch the data in an Observable before setting up the autocomplete and utilized the async pipe in the HTML, but unfortunately, the data does not update based on valueChanges with this approach. Even when trying to update the observable post switchMap, the issue persists.
Any advice would be greatly appreciated. Thank you.