【发布时间】:2022-01-27 17:23:57
【问题描述】:
我从 API 完成了有关 Angular 自动完成的所有教程,以便能够重现这些步骤。 valuechanges 监听表单控件,触发 switchmap 以重新发送每个新关键字的请求,然后将数据加载到自动完成。它正在工作,但在加载来自服务的最后一个请求后,我需要执行一个操作(计时或打字)以查看自动完成下拉列表中响应的最后一个结果。我在一个新的 Angular 项目上对其进行了测试,我没有这个问题。我的 Angular 版本是 10。
加载数据的代码:
// 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 = [];
}
html:
<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>
我不知道为什么我需要执行操作才能在自动完成下拉列表中查看我的请求的最后结果(对象数组)。
在加载自动完成之前,我尝试将数据加载到 Observable 中,并在 html 中使用异步管道,但当然使用此解决方案,数据不会因 valuechanges 而改变。即使我用这种方法(在 switchmap 之后)更新 observable 我也有同样的问题。
感谢您的建议。
【问题讨论】:
标签: angular typescript angular-material autocomplete