DasPete
DasPete

Reputation: 851

Angular focus on select element

I am trying to programmatically focus on a select element with angular. Here is my code:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@ViewChild('microwaveRef') microwaveElement: ElementRef
this.microwaveElement.nativeElement.focus()

On the HTML side:

<mat-form-field class='login-full-width'>
    <mat-label>Microwave</mat-label>
    <mat-select #microwaveRef [formControl]="microwaveFormControl" required>
        <mat-option *ngFor="let option of microwave" [value]="option">
            {{option}}
        </mat-option>
    </mat-select>
    <mat-error *ngIf='microwaveFormControl.hasError("required")'>
        Please select an option for the Microwave field
    </mat-error>
</mat-form-field>

This has worked well with a text input field, but with the select I receive this error:

ERROR TypeError: Cannot read property 'focus' of undefined

Any help would be much appreciated

Upvotes: 1

Views: 8725

Answers (1)

JossFD
JossFD

Reputation: 2216

It's undefined because nativeElement doesn't exist directly on a mat-select. An alternative is to use to focused property on the mat-select and set it to true yourself:

this.microwaveElement.focused = true

I provided a Stackblitz example to demonstrate this.


Edit:

Actually, the mat-select has a focus() function of its own, so you can use:

this.microwaveElement.focus();

Or even:

this.microwaveElement.open();

Upvotes: 2

Related Questions