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

时间:2019-12-30 14:39:04

标签: angular angular-material

我在表单中使用了以下angular组件,以向具有多个选择功能的angular material select组件添加了自动完成功能: https://github.com/malothnaresh/mat-select-autocomplete

它工作正常,我可以搜索选项列表进行选择。 但是现在我需要,当我单击列表时,默认情况下焦点应该在列表选项(列表中第一个选项之上)顶部显示的搜索框中,而不是列表中的任何选定选项(当前行为) 。因为到目前为止,如果列表很长,那么我必须向上滚动然后单击搜索框,然后再开始搜索任何特定选项。

有人可以建议我针对搜索框的任何设置方法吗?

下面给出了我为使用自动完成组件而应用的角度代码。

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>

1 个答案:

答案 0 :(得分:0)

您可以手动对焦:

添加ID,以便您可以使用document.getElementById

进行选择
<mat-select-autocomplete id="autocomplete" ...

然后将选择重点放在:

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