首页 > 解决方案 > Angular Material Autocomplete:onfocus 保持建议面板关闭

问题描述

我正在使用 Angular Material 7.3.7,并且我有一个类似于文档中的简单自动完成功能:

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

当输入变得集中时,有什么方法可以关闭建议面板?

我已经通过 API 进行了搜索,但没有发现任何有用的信息。

提前致谢!

标签: angularangular-materialonfocus

解决方案


这是一个有点hacky的解决方案,但您可以使用 MatAutocompleteTrigger 的 closePanel 方法,如下所示

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input #inp="matAutocompleteTrigger"
           (focus)="inputFocused(inp)"
           type="text"
           placeholder="Pick one"
           aria-label="Number"
           matInput [formControl]="myControl"
           [matAutocomplete]="auto"
    />
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

然后将以下方法添加到您的 ts 文件中

focused(trg: MatAutocompleteTrigger) {
  setTimeout(() => {
    trg.closePanel();
  });
}

通过使用 settimeout,我们正在等待下一个更改检测周期,以便面板打开,然后我们将其关闭。结果面板在几毫秒内打开和关闭。

希望能帮助到你 :)

===非hacky解决方案====

我检查了我的自动完成实现,在其中一个我们有大量选项的地方,我们使用了两个选项数组,一个是allOptions另一个filteredOptions。filtersOptions 最初是空的,我在模板中只显示了 filteredOptions。因此,除非用户键入要输入的内容,否则不会显示任何内容(实际上我强制至少两个字符开始过滤,因为 allOptions 有几千个选项)。

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text"
           placeholder="Pick one"
           aria-label="Number"
           matInput
           [formControl]="myControl"
           [matAutocomplete]="auto"
    />
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

在我的 ts 文件中;

allOptions: string[] = this.dataService.userOptions; // there are thousands of options
filteredOptions: string[] = [];

ngOnInit() {
  this.myControl.valueChanges.subscribe(z => {
    if (!z || z.length < 2) {
      this.filteredOptions = [];
    } else {
      this.filteredOptions = this.allOptions.filter(el => el.toLowerCase().indexOf(z.toLowerCase()) >= 0);
    }
}

我希望这有助于更多:)


推荐阅读