【问题标题】:How to set auto focus in mat-select?如何在 mat-select 中设置自动对焦?
【发布时间】:2023-03-07 02:00:01
【问题描述】:

在我的角度项目中,有角度材料并使用 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>

【问题讨论】:

标签: javascript angular typescript angular-material


【解决方案1】:

我们可以使用默认的角度属性进行自动对焦

<mat-form-field>
    <mat-select formControlName="xyz" cdkFocusInitial>
        <mat-option value="abc">Abc</mat-option>
    </mat-select>
</mat-form-field>

【讨论】:

  • 警告:cdkFocusInitial 自己不会做任何事情。它只能在带有cdkTrapFocus 指令的元素内工作。
【解决方案2】:

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

ngAfterViewInit

HTML:

<mat-select #fff>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
</mat-select>

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;
  }
}

查找工作演示 here。您可以看到 select 已突出显示。在 ngAfterViewInit() 中注释代码并查看其中的差异。

【讨论】:

  • 感谢@Harshad vekariya,它工作正常
  • ngFor 的工作原理。我想关注 0 索引垫下拉菜单
【解决方案3】:

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();
}

希望这会有所帮助。

【讨论】:

  • 最好在this.someRef上添加真实检查
  • 在 Angular 9 上使用 ElementRef 对我不起作用,但 MatSelect 成功了。谢谢。
【解决方案4】:

首先,让我们创建指令 auto-focus.directive.ts

import { AfterContentInit, Directive, ElementRef, Input } from '@angular/core';

@Directive({
     selector: '[autoFocus]' }) export class AutofocusDirective implements AfterContentInit {

     public constructor(private el: ElementRef) {     
     }

     public ngAfterContentInit() {
         setTimeout(() => {
             this.el.nativeElement.focus();
         }, 500);
     }
}

接下来我们需要告诉我们的 AppModule 这个新指令存在,并通过更新我们的 app.module.ts 来声明它的可用性:

@NgModule({
    declarations: [
        AutoFocusDirective
    ]
})

现在您可以在组件模板中使用它: app.component.html

<div> Autofocus? <input appAutoFocus> </div>

【讨论】:

    【解决方案5】:

    由于这是出现在 Google 上的第一个点击,我将提供我发现的内容:

    请注意,我专门为 mat-select 执行此操作,因为没有可以将引用附加到的 真实 内部 html 元素

    我发现的工作是通过view-child 获取对元素的引用,然后调用

    reference._elementRef.nativeElement.focus();
    

    希望这至少对某人有所帮助:)

    【讨论】:

      【解决方案6】:

      尝试在viewChild 上使用MatSelect 来访问focused 属性,然后onInit 将其设置为true。

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

      和ts文件导入import { MatSelect } from '@angular/material';

      import { MatSelect } from '@angular/material';
      
      export class SelectExample implements OnInit {
        @ViewChild(MatSelect) mySelect: MatSelect;
      
        ngOnInit() {
          this.mySelect.focused = true;
        }  
      }
      

      【讨论】:

      • 这在不正确的 AFAIK 中。它将样式设置为focused,但这实际上并没有聚焦元素!
      【解决方案7】:

      您可以拨打关注OnInit

      ts:

       options2 = ['A', 'B'];
      
        @ViewChild('name')
        nameField: MdSelect;
      
        ngOnInit() {
          setTimeout(() => {
            this.nameField.open();
          }, 0);
        }
      

      html:

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

      编辑:抱歉,我认为您无法从 mat-selectmd-select 获得 nativeElement。您需要获取对象并调用open()。 工作项目here in stackblitz

      【讨论】:

      • 我已经尝试过这种方式,但它不起作用,它仅适用于输入元素而不适用于 mat-select
      【解决方案8】:

      您可以将此示例改编为您自己的项目。点击按钮成为焦点。

      focusing on form elements the Angular way

      show more

      【讨论】:

      最近更新 更多