如何在mat-select中设置自动对焦?

Blu*_*oud 6 javascript typescript angular-material angular

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

@ViewChild("name") nameField: ElementRef;

ngOninit() {
  this.nameField.nativeElement.focus();
} 
Run Code Online (Sandbox Code Playgroud)

HTML

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

Lah*_*ana 5

HTML :

<mat-select #someRef >
    <mat-option *ngFor="let item of items;" [value]="item">
    {{item.name}}
    </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

.ts :确保您导入MatSelect

import { MatSelect } from '@angular/material';
Run Code Online (Sandbox Code Playgroud)
@ViewChild('someRef') someRef: MatSelect;


ngOnInit() {
    if(this.someRef) this.someRef.focus();
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。


Har*_*iya 3

如果我理解正确的话,您希望将选择元素集中在加载上。如果是这种情况,您的代码完全没问题,您只需将焦点逻辑移至另一个生命周期事件即可

ngAfterViewInit

HTML:

<mat-select #fff>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
</mat-select>
Run Code Online (Sandbox Code Playgroud)

TS:

export class SelectOverviewExample  implements AfterViewInit{
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

  @ViewChild("fff", {static: false}) nameField: ElementRef;

  ngAfterViewInit() {
    this.nameField.focused = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

在这里找到工作演示。您可以看到选择已突出显示。注释 ngAfterViewInit() 内的代码并查看此差异。

  • 谢谢@Harshad vekariya,它按预期工作正常 (2认同)