12

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>
Nenad Radak
  • 3,550
  • 2
  • 27
  • 36
BlueCloud
  • 523
  • 2
  • 5
  • 15

8 Answers8

10

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.

Lahiru Udana
  • 105
  • 1
  • 8
3

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.

Harshad Vekariya
  • 972
  • 1
  • 7
  • 28
2

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 :)

Elias
  • 3,592
  • 2
  • 19
  • 42
2

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>
Akshay Garg
  • 1,010
  • 8
  • 15
  • 2
    Caveat: `cdkFocusInitial` doesn't do anything on its own. It will only work inside an element with the `cdkTrapFocus` directive on it. – j2L4e Feb 22 '20 at 20:30
1

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;
  }  
}
Nenad Radak
  • 3,550
  • 2
  • 27
  • 36
  • This in incorrect AFAIK. It sets the style to `focused` but this not actually focuses the element! – Elias May 28 '19 at 08:24
0

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

Gaspar
  • 1,515
  • 13
  • 20
0

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>
Ashish Kamble
  • 2,555
  • 3
  • 21
  • 29
RahulD
  • 729
  • 5
  • 8
-1

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

focusing on form elements the Angular way

show more

umutyerebakmaz
  • 887
  • 8
  • 18
  • 1
    [Providing a link to an answer is not a good way of answering a question](https://meta.stackexchange.com/q/225370/194720). Please include the relevant code, if the site's license allows, here on Stack Overflow. You can likely use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) to provide a runnable snippet. – Heretic Monkey Feb 08 '19 at 14:16
  • I already tried that way but its not working its only working for input elements not for mat-select – BlueCloud Feb 08 '19 at 14:25