-1

I was asked to update on a frontend application with Angular 8 to set autofocus on a particular element. Basically, this app would prompt user to enter a question and the app would display some result text which needs to be focused.

I have searched and tried a few suggestions using Angular autofocus directives but not succeed. I find a lot of samples on using autofocus for input field but not for div.

Is it possible to set autofocus on this element without reloading the page? If so, how do I do that?

Update - I found this tutorial but it doesn't exactly do as I hoped. I thought the input field should automatically be focused when the page is loaded. However, it's only focused if I have to click/tab.
https://www.codementor.io/@yomateo/auto-focus-with-angular-7-the-directive-osfcl7rrv

Is there a way to have autofocus on the field without actual click or tab?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
J.TrLu
  • 65
  • 1
  • 12
  • Please post yout code what you have tried so far. It will help in providing the solution or rectify if there is anything wrong in the code. – Satwinder Singh Apr 06 '21 at 22:32

2 Answers2

0

Couple of things

  • make sure the code you are ttying to focus on input field is correct. You can check it out by calling on some button click.
  • check calling this code inside some different lifecycle hook such as ngAfterContentInit() , ngAfterViewChecked() or any other.
  • If 2nd point doesn't help then try putting your code inside timeout.
Satwinder Singh
  • 229
  • 2
  • 9
-1

You can use cdkTrapFocusAutoCapture from @angular/cdk

Mehdi Shakeri
  • 584
  • 3
  • 11