简体   繁体   English

Angular2:尝试使用@ViewChild 注释将焦点设置到输入字段时出现未定义的错误

[英]Angular2: undefined errors when trying to set focus to an input field using @ViewChild annotation

I have a input field which I set focus to when my view loads in the following way:我有一个输入字段,当我的视图以以下方式加载时,我将焦点设置为:

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

this works fine from within the ngAfterViewInit() function but when I try to do it in another part of my view when a button is clicked I get an exception saying that focusInput is undefined.这在 ngAfterViewInit() 函数中工作正常,但是当我尝试在我的视图的另一部分单击按钮时执行此操作时,我收到一个异常,说 focusInput 未定义。 After reading up a bit it seems like ngIf could be the cause of this as the part of the view that contains the input field #focusInput gets shown or hidden using ngIf.在阅读了一些之后,似乎 ngIf 可能是导致此问题的原因,因为包含输入字段 #focusInput 的视图部分使用 ngIf 显示或隐藏。 Is there any way I can check using ngOnChanges() or anything else whether the #focusInput input field is currently shown and if it is set focus to it?有什么方法可以使用 ngOnChanges() 或其他任何方法检查 #focusInput 输入字段当前是否显示以及是否将焦点设置为它?

It happens when you have ngIf or ngFor directives inside your template and your input can not be linked to focusInput property you added inside your class.当您的模板中有ngIfngFor指令并且您的输入无法链接到您在类中添加的focusInput属性时,就会发生这种情况。 Instead use this code:而是使用此代码:

<input type="text" #myInput />
{{ myInput.focus() }}

Just add {{ myInput.focus() }} right after input inside template只需在模板中输入后立即添加{{ myInput.focus() }}

The simplest solution turned out to be writing a custom focus attribute directive.结果证明,最简单的解决方案是编写自定义焦点属性指令。 This helped a lot:这有很大帮助:

How to move focus on form elements the Angular way 如何以 Angular 的方式将焦点转移到表单元素上

I know its very late to answer your question.我知道现在回答你的问题已经很晚了。 If you want focus after any click or view change so for this you need to call change detector.如果您想在任何单击或视图更改后获得焦点,那么为此您需要调用更改检测器。 You can call change detection after your view change or a click by calling detectchanges().您可以在视图更改或单击后通过调用 detectchanges() 调用更改检测。

`constructor(private detRef:ChangeDetectorRef) {}
  @ViewChild('name_input') input: ElementRef;

    private buttonClick(): void {
      this.detRef.detectChanges();
      this.input.nativeElement.focus();
    }`

Hope this will helpful.希望这会有所帮助。

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

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