【问题标题】:How we set focus on input element in angular7我们如何在angular7中将焦点放在输入元素上
【发布时间】:2019-08-08 09:26:28
【问题描述】:

我已经在 ts 文件中导入了 ViewChild,ElementRef,Renderer 但它显示错误“ERROR TypeError: Cannot read property 'nativeElement' of undefined”

import { Component, OnInit,ViewChild,ElementRef,Renderer } from '@angular/core';

@ViewChild('usernameField') input : ElementRef;

this.usernameField.nativeElement.focusIn();

期望关注输入元素。

【问题讨论】:

  • 也发布你的html
  • 你的变量是this.input,不是this.usernameField,函数是focus()不是focusIn()

标签: angular angular7


【解决方案1】:

我认为这会奏效

代替

this.usernameField.nativeElement.focusIn();

试试

this.usernameField.nativeElement.focus();

或者发布您的 html 以便我们查看问题所在?

只需检查您的输入标签#usernameField

喜欢

<input #usernameField

然后改变你的 ts

@ViewChild('usernameField') usernameField: ElementRef;

还要确保你在ngAfterViewInit中添加了焦点

喜欢

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

【讨论】:

  • Html 代码:
  • 有时我会用他的伎俩分享支票?stackblitz.com/edit/angular-viewchild-static??
  • @malbarmawi 坦率地说,我不喜欢setTimeout hack :(,我们不能相信它。所以除非非常必要,否则我会避免使用它:P
  • agred ?? 新版本的 Angular 8 已经通过静态属性修复了这个技巧
  • 但在所有情况下超时功能都会在 ngAfterViewInit 之后运行 ??
【解决方案2】:

input 将在ngAfterViewInit 运行时设置,这意味着你不能像在 ngOnInit() 方法中那样使用之前的值将是 undefined

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

角度 verion 8+ ??

@ViewChild('usernameField',{static : true}) usernameField: ElementRef;

ngOnInit() {
 this.usernameField.nativeElement.focus();
}

检查这个?How should I use the new static option for @ViewChild in Angular 8?

check this live demo ?‍♂️?‍♂️

【讨论】:

    【解决方案3】:

    只需在构造函数中注入 ElementRef。

    constructor(private el:ElementRef){ this.el.nativeElement.querySelector('input[type:"text"]').focus(); }

    【讨论】:

    • 我们无法在constructor....中给予焦点。因为在构造函数执行期间视图不可用
    • 是的。请将同一行代码添加到 ngAfterViewInit()