首页 > 解决方案 > 点击后清空Angular typeahead输入

问题描述

我有一个预先输入的下拉菜单,当你点击它时它会显示过期的值,所以我想让它在点击它时什么都不显示(直到你输入)。预输入功能本身正在工作。

最初我认为必须在我的组件文件中进行更改(例如清空字段),但看起来它可能在模板中进行(或在 comp 和模板文件中)。

我对 Angular 很陌生,所以如果我的语法/代码/等生锈了,我深表歉意。

组件文件:

// locations
  filteredLocations: Observable<any[]>;
  filteredUserLocations: Observable<any[]>;
  locationTargeting = 'My Location';

getMyLocations(search: string): void {
    const user = this.auth.account$.getValue();
    if (!search.includes(';') && this.locationTargeting === 'My Location') {
// this.filteredUserLocations = new Observable<any[]>(); // tried setting this here (and in other locations), but the typeahead history still appears
      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 = new Observable<any[]>();
    }
  }


服务文件:

getTypeaheadLocationsByValue(
    value: string,
    accountId: string,
    accountIds: string[] = null,
    groupIds: string[] = null
  ): Observable<CollectionResponse<LocationSearchResponse>> {
    const searchLocationTypeahead: SearchLocationsTypeaheadByValueRequest = new SearchLocationsTypeaheadByValueRequest();
    if (accountIds) {
      // etc
    }
    if (groupIds) {
      // etc
    }
    searchLocationTypeahead.value = value;
    searchLocationTypeahead.accountId = accountId;

    return this.http.post<CollectionResponse<LocationSearchResponse>>('my-url', searchLocationTypeahead);
  }

模板文件:

          <div *ngIf="hasLocationTargeting" class="add-container">
            <mat-form-field>
              <input autofocus matInput formControlName="locationToAdd"
                data-atm="target-locations-input" [matAutocomplete]="location">
            </mat-form-field>
          </div>

标签: angularinputrxjsobservabletypeahead

解决方案


有多种处理方法。一种这样的方法是最初将值设置为 null / 空数组。你可以这样做:

// locations
  filteredLocations: Observable<any[]>;
  filteredUserLocations: Observable<any[]>;
  locationTargeting = 'My Location';

getMyLocations(search: string): void {
/********* Before you do the actual search, set the observable to null ******/
this.filteredUserLocations = of([]); // This will initially have an empty array and then you can set the value when you want
    

const user = this.auth.account$.getValue();
    if (!search.includes(';') && this.locationTargeting === 'My Location') {
    
this.filteredUserLocations = this.locationService
      .getTypeaheadLocationsByValue(....)

推荐阅读