简体   繁体   English

如何在带有自动完成功能的 mat-select 的搜索框中设置焦点?

[英]How to set focus in the search box of mat-select with autocomplete?

I used following angular component in my form to add autocomplete feature to angular material select component with multiple selection feature: https://github.com/malothnaresh/mat-select-autocomplete我在表单中使用以下angular组件向具有多项选择功能的angular material select组件添加自动完成功能: https : //github.com/malothnaresh/mat-select-autocomplete

It is working properly and I can search the list of options for selection.它工作正常,我可以搜索选项列表以供选择。 But now I need that when I click on the list, the focus should be in the search box displayed on top of the list options(above first option in the list) by default, instead of any selected option in the list(current behavior).但是现在我需要,当我点击列表时,焦点应该在默认情况下显示在列表选项(列表中的第一个选项上方)顶部的搜索框中,而不是列表中的任何选定选项(当前行为) . Because as for now if the list is long then I have to scroll upwards and then click in the search box before starting to search for any specific option.因为就目前而言,如果列表很长,那么我必须向上滚动,然后在开始搜索任何特定选项之前单击搜索框。

Can anyone suggest me any solutions for settings focus on the search box.任何人都可以向我建议任何针对搜索框的设置解决方案。

The angular code I applied to use the autocomplete component is given below.下面给出了我用于使用自动完成组件的 angular 代码。

 export type ListOption = { displayName: string, value: number } itemList: ListOption[] = []; itemValues: any[] = []; // Refer the multi-select list with viewchild @ViewChild(SelectAutocompleteComponent) multiSelect: SelectAutocompleteComponent; ngOnInit(): void { this.itemList.push({ displayName: 'item1', value: 1 }); this.itemList.push({ displayName: 'item2', value: 2 }); ... getList(event) { this.itemValues = event; } onClick() { //I tried to set focus using this code. But I know it will not work. As I still need to fetch reference of the inner search text box. let innerControl = this.multiSelect.selectElem; innerControl.focused = true; } }
 <mat-select-autocomplete appearance="outline" name="myList" [required]='true' [placeholder]="'Select item(s):'" [options]="itemList" [multiple]='true' [display]="'displayName'" [value]="'value'" [selectedOptions]="itemValues" (selectionChange)="getList($event)" (click)="onClick()"> </mat-select-autocomplete>

You can focus manually:您可以手动对焦:

Add an id so you can select it with document.getElementById添加一个 id,以便您可以使用document.getElementById选择它

<mat-select-autocomplete id="autocomplete" ...

Then focus the select with:然后聚焦选择:

document.getElementById('autocomplete').focus();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM