0

I'm trying to control the button focus without using the tag autofocus=true, but it seems that doesn't work properly, do you think is necessary a pipe?

 <button #btn_focus>

 @ViewChild('btn_focus') firstNameElement: ElementRef;

  ngAfterViewInit(){
    this.firstNameElement.nativeElement.focus();
  }

Thanks.

Gelso77
  • 1,763
  • 6
  • 30
  • 47

2 Answers2

0

I also have the same problem tried multiple ways but not worked. finally, I used javascript code to focus on given HTML element with attribute id.

function focusInputelement(id) {
        window.setTimeout(() => {
              document.getElementById(id).focus();
        }, 500);
    }
mahesh kajale
  • 510
  • 1
  • 5
  • 17
  • I was having a similar problem but I'm on angular 15. I have a disabled input element that I wanted to get focused after button click since that button click was doing other things too. The `this.myInput.nativeElement.focus()` didn't work until I wrapped it in a `setTimeout(...)` – redeemefy Dec 15 '22 at 03:12
0

Your code is working, you can see it in action here:

https://stackblitz.com/edit/angular-6mszhb?file=app%2Fapp.component.ts

I bet your problem is just opened developer console, that steals the focus right after page is loaded. Try to open that stackblitz with developer console closed (works), than open the console (and have it focused, so your cursor is blinking there) and refresh the page (will not work).

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64
  • thank you so much i really appreciate , but from my side i have this error NgtableComponent.html:38 ERROR TypeError: Cannot read property 'nativeElement' of undefined, maybe because i am working with a modal page ? – Gelso77 Apr 25 '18 at 13:47
  • well without the code its hard to tell. try to reproduce that error in stackblitz – Martin Adámek Apr 25 '18 at 13:51