Autofocus not working on chrome in angular 10

1.5k Views Asked by At

I am trying to autofocus on to login id after incorrect login id and password message is displayed and announced on VOICE OVER/talk back.

It should shift focus to login id text field. to make sure my application ADA and 508 Compliance.

<input id="loginID" tabindex="0" autofocus matInput type="text" #userId placeholder="{{'LoginPage.UserID' | translate}}" ngModel
 formControlName="userId" required aria-required="true" aria-label="userId is mandatory field" aria-describedby="userIdValidationMsg">

Autofocus not working on chrome. Is there any suggestions to end up my search on this autofocus on google for angular 10.

open for Suggestion on implementing the same solution in some other Approach.

1

There are 1 best solutions below

0
slugolicious On

autofocus is typically used on page load. In your case, it sounds like the page is already loaded, then the user types an incorrect login, and then you add autofocus dynamically? If so, that's not the intended use of autofocus. Instead, you can use javascript focus() on the <input>.

document.getElementById('loginID').focus();

Side note, you don't need tabindex="0" on the <input> because it's natively keyboard focusable.

Also, be careful if you have both an aria-label and a <label> element. The aria-label will "win" and the <label> will be ignored. Your code example doesn't show a <label> but does use aria-label so I wanted to mention it just in case.