mat-autocomplete 仅在搜索文本上显示列表

我正在构建一个应用程序并且我有 mat-autocomplete。我只想在输入文本字段中输入某些文本时显示搜索列表。我尝试了某些方法但没有运气

 <mat-form-field class="example-full-width" appearance="fill">
        <mat-label>Assignee</mat-label>
        <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
            {{option.name}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
dangfangxia 回答:mat-autocomplete 仅在搜索文本上显示列表

你必须在 component.ts 中创建函数,然后它才能正常工作。分别按照以下步骤操作。

HTML 组件

<mat-form-field class="example-full-width" appearance="fill">
        <mat-label>Assignee</mat-label>
        <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
            {{option.name}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>

在构造函数中插入以下代码。

this.filteredOptions = this.myControl?.valueChanges.pipe(
      startWith(''),map(value => this._filter(value))
);

创建一个名为 _filter 的方法来获取所有自动完成值。

_filter(value: any): any[] {
    const filterValue = value.toLowerCase();
    return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}

重要 - 确保 this.options 表示所有受让人

本文链接:https://www.f2er.com/7542.html

大家都在问