如何实现点击时清空Angular typeahead输入框的过时下拉选项
解决方案
你遇到的问题核心是两个原因:
- 点击输入框触发自动过滤时,空搜索值依然会走接口逻辑返回旧数据,且你之前用
new Observable<any[]>()属于冷Observable,不会主动发射值,autocomplete会保留上一次的渲染结果 - 没有针对输入框的点击/焦点事件做主动清空逻辑
1. 组件代码修改
首先从rxjs导入of工具方法:
import { of } from 'rxjs';
修改getMyLocations方法,新增空搜索值拦截逻辑:
getMyLocations(search: string): void { // 新增:空搜索值直接返回空结果,不调用后端接口 if (!search?.trim()) { this.filteredUserLocations = of([]); return; } const user = this.auth.account$.getValue(); if (!search.includes(';') && this.locationTargeting === 'My Location') { this.filteredUserLocations = this.locationService .getTypeaheadLocationsByValue( search, // value user.id, // accountId null, // accountIds this.targetingFormGroup.get('groups')?.value) // groupIds .pipe(map((result: CollectionResponse<LocationSearchResponse>) => { if (result.list) { result.list.map((location) => this.addToLocationCache(location.id, location.locationNumber, location.name)); } return result.list && result.list.length > 0 ? [{ label: 'User Locations', values: (result.list || []) }] : []; })); } else { this.filteredUserLocations = of([]); } }
新增焦点事件触发的清空方法:
clearLocationOptionsOnFocus(): void { const inputVal = this.targetingFormGroup.get('locationToAdd')?.value; // 输入框无内容时主动清空下拉选项 if (!inputVal?.trim()) { this.filteredUserLocations = of([]); } }
2. 模板代码修改
给输入框新增焦点事件绑定:
<div *ngIf="hasLocationTargeting" class="add-container"> <mat-form-field> <input autofocus matInput formControlName="locationToAdd" data-atm="target-locations-input" [matAutocomplete]="location" (focus)="clearLocationOptionsOnFocus()"> </mat-form-field> </div>
同时确认你的mat-autocomplete组件绑定了async管道来订阅异步结果流,示例参考:
<mat-autocomplete #location="matAutocomplete"> <mat-optgroup *ngFor="let group of filteredUserLocations | async" [label]="group.label"> <mat-option *ngFor="let loc of group.values" [value]="loc.name"> {{ loc.name }} </mat-option> </mat-optgroup> </mat-autocomplete>
内容的提问来源于stack exchange,提问作者Bodrov
相关产品推荐
相关产品推荐

