javascript - 如何在 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>
解决方案
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();
}
希望这可以帮助。
推荐阅读
- database - 数据建模和维度建模有什么区别?
- typeorm - 使用 Typeorm 查找未引用的对象
- git - 取消合并分支以便重新合并的最佳实践?
- authorization - 具有 client_credentials 身份验证的守护程序应用程序如何从特定用户获得委托权限?
- python - Python PyQt 信号并不总是有效
- python - 抓取特定标签的 Scrapy 问题
- python - python中的并行查询,在kubernetes中有一个文件和几个pod
- node.js - 带有 express 的 Certbot 通配符
- c++ - 在 vscode 上选择 c++(GDB/LLDB) 时,我收到无法读取未定义错误的属性“包含”
- java - 在窗口 10 上设置外部工具时,Intellij 在 $FilePath$ 之前添加用户主路径