简体   繁体   中英

How to set auto focus in mat-select?

In my angular project have angular material and use mat-select. Mat-select is the first element for my form in my case set auto focus while page was loaded successfully but I wasn't able to set auto focus on mat-select. Anyone can help me to find the way to set auto focus in 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 : make sure you import MatSelect

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


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

Hope this helps.

If I understand it correctly, you want to focus select element on load. If this is the case, your code is perfectly fine, you just need to move focus logic in to another life cycle event which is

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

Find working demo here . You can see select is highlighted. comment code inside ngAfterViewInit() and see this difference.

As this is the First hit that shows up on Google I'll provide what I found:

Note that I did this specifically for a mat-select as there is no real inner html element that the reference could be attached to .

What I found works is getting a reference to the element through view-child and then calling

reference._elementRef.nativeElement.focus();

Hope this helps at least someone :)

We can use default angular attribute for autofocus

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

Try using MatSelect on viewChild to access focused attribute, then onInit set it to 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>

and ts file import import { MatSelect } from '@angular/material';

import { MatSelect } from '@angular/material';

export class SelectExample implements OnInit {
  @ViewChild(MatSelect) mySelect: MatSelect;

  ngOnInit() {
    this.mySelect.focused = true;
  }  
}

You can call the focus on 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>

EDIT: Sorry, I think you can not get the nativeElement from mat-select and md-select . You need to get the object and call open() . Workning project here in stackblitz

First, let's create the Directive 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);
     }
}

Next we need to tell our AppModule that this new directive exists and to declare it for availability by updating our app.module.ts :

@NgModule({
    declarations: [
        AutoFocusDirective
    ]
})

Now you can use it in a component template: app.component.html

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

You can adapt this example to your own project. Clicking on the button becomes focus.

focusing on form elements the Angular way

show more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM