简体   繁体   English

角度4:Viewchild设定焦点

[英]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? 我试图在不使用标签autofocus = true的情况下控制按钮的焦点,但是似乎无法正常工作,您是否认为有必要使用管道?

 <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. 最后,我使用javascript代码专注于具有属性ID的给定HTML元素。

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 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). 尝试在关闭(开发人员)开发人员控制台的情况下打开该stackblitz,然后打开控制台(并使其聚焦,因此您的光标在那里闪烁)并刷新页面(不起作用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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