angular - 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 进行了搜索,但没有发现任何有用的信息。
提前致谢!
解决方案
这是一个有点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);
}
}
我希望这有助于更多:)
推荐阅读
- firebase - 克隆 Firebase 配置时权限被拒绝
- r - 如何根据其中一列对数据框进行排序?
- c - 在自己的 sizeof API 中需要 (char*) 类型转换吗?
- sql - 与同一张表的三元关联
- excel - 我想在一个单元格中使用 2 个公式。如果一个公式返回 0 值,我想使用另一个公式返回值
- java - 我可以在 split() 中使用字符串数组来指定分隔符吗?
- java - Hibernate @OneToOne 加载即使是懒惰的
- javascript - 使用 HTTP 请求连续运行 node.js 文件
- php - 指数数排序的 PHP 算法 (a^b)
- javascript - 生成器函数中的多次提取