简体   繁体   中英

Angular 4: Viewchild set focus

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.

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);
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM