代码之家  ›  专栏  ›  技术社区  ›  James Bender

mat autocomplete:选择后需要重置选项列表

  •  0
  • James Bender  · 技术社区  · 5 年前

    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="areaSelected($event.option.value)">
          <mat-option *ngFor="let option of options" [value]="option">{{ option }}</mat-option>
    </mat-autocomplete>

    在我的TS代码中,当用户选择一个值时,在处理结束时,我将options数组设置为空数组:

      resetFetchedOptions() {
        this.options = [];
    }

    谢谢!

    1 回复  |  直到 5 年前
        1
  •  3
  •   DaggeJ    5 年前

    你用的是反应形式吗?我做了类似的事情( based on this article

    html格式

    <mat-form-field class="width-filler">
        <input type="text" matInput placeholder="Search" [matAutocomplete]="auto" [formControl]="formControl" autocomplete="off" autofocus>
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFunc">
            <mat-option *ngIf="isSearching" class="is-loading"><mat-spinner diameter="20"></mat-spinner></mat-option>
            <mat-option *ngFor="let result of filteredResult" [value]="result">
                {{result.description}}
            </mat-option>
        </mat-autocomplete>
        <mat-hint>{{searchHint()}}</mat-hint>
    </mat-form-field>
    

    打字稿

    ngOnInit() {
        this.formControl
            .valueChanges
            .pipe(
                debounceTime(300),
                tap(() => this.isSearching = true),
                switchMap(value => this.someService.searchStuff<ResultType[]>(this.getSearchString(value as any))
                    .pipe(
                        finalize(() => this.isSearching = false),
                    )
                )
            )
            .subscribe(result => this.filteredResult = result);
    
        this.formControl.valueChanges.subscribe(value => this.setValue(value));
    }
    
    // Need to handle both the search string and a selected full type
    private setValue(value: string | ResultType) : void {
        if (typeof value === "string")
            this.selectedValue = null;
        else
            this.selectedValue = value;
    }
    
    private getSearchString(value: string | ResultType) {
        if (typeof value === "string")
            return value;
        else
            return value.description;
    }
    
        2
  •  1
  •   Javier Aviles    5 年前

    this.options.length=0 而不是 = []