11
votes

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>
8
[focused]="true"?quirimmo
You have to use a directive for that purpose. Check this answer: stackoverflow.com/a/44729559/7630248Chris Tapay
Please include the code you've tried, here on Stack Overflow.Heretic Monkey
I still can't figure it out why you picked up my answer and put inside the questionGaspar

8 Answers

5
votes

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.

3
votes

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.

2
votes

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

2
votes

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>
1
votes

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

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

0
votes

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>
-1
votes

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

focusing on form elements the Angular way

show more