首页 > 解决方案 > 我们如何在 angular7 中将焦点放在输入元素上

问题描述

我已经在 ts 文件中导入了 ViewChild、ElementRef、Renderer,但它显示错误“错误类型错误:无法读取未定义的属性‘nativeElement’”

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

@ViewChild('usernameField') input : ElementRef;

this.usernameField.nativeElement.focusIn();

期望专注于输入元素。

标签: angularangular7

解决方案


我认为这会奏效

代替

this.usernameField.nativeElement.focusIn();

尝试

this.usernameField.nativeElement.focus();

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

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

喜欢

<input #usernameField

并改变你的 ts

@ViewChild('usernameField') usernameField: ElementRef;

还要确保您已将焦点添加到ngAfterViewInit

喜欢

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

推荐阅读