首页 > 解决方案 > 如何在 mat-select 中设置自动对焦?

问题描述

在我的角度项目中,有角度材料并使用 mat-select。在我的案例中,Mat-select 是我的表单的第一个元素,当页面成功加载时设置自动焦点,但我无法在 mat-select 上设置自动焦点。任何人都可以帮助我找到在 mat-select 中设置自动对焦的方法。

@ViewChild("name") nameField: ElementRef;

ngOninit() {
  this.nameField.nativeElement.focus();
} 

html

<div>
 <mat-select [(ngModel)]="nameField" #name>
    <mat-option *ngFor="let option of options2" [value]="option.id">
      {{ option.name }}
    </mat-option>
 </mat-select>
</div>

标签: javascriptangulartypescriptangular-material

解决方案


HTML:

<mat-select #someRef >
    <mat-option *ngFor="let item of items;" [value]="item">
    {{item.name}}
    </mat-option>
</mat-select>

.ts :确保导入MatSelect

import { MatSelect } from '@angular/material';
@ViewChild('someRef') someRef: MatSelect;


ngOnInit() {
    if(this.someRef) this.someRef.focus();
}

希望这可以帮助。


推荐阅读