繁体   English   中英

Angular 8 - 访问 ngOnInit 中的元素时无法读取 null 的属性“焦点”

[英]Angular 8 - Cannot read property 'focus' of null when accessing an element in ngOnInit

我有以下 html (modal-login.component.html):

<input placeholder="Password" id="password" type="password" formControlName="password" class="form-input" #loginFormPassword />

这是我来自 ts 文件(modal-login.component.ts)的代码:

ngOnInit() {
    for (const key of Object.keys(this.loginForm.controls)) {
        if (this.loginForm.controls[key].invalid) {
            // here key value is "password"
            const invalidControl = this.el.nativeElement.querySelector('[formcontrolname="' + key + '"]');
            invalidControl.focus(); //Here it gives me the error in console
            break;
        }
    }
}

我正在尝试以下操作,但无法正常工作,我没有收到错误消息,但输入密码未捕获焦点:

  public ngAfterViewInit(): void {
    console.log(this.el.nativeElement);
    this.el.nativeElement.focus();
  }

但我在浏览器控制台中收到以下错误:

core.js:6014 ERROR TypeError: Cannot read property 'focus' of null

可能是什么问题呢? 谢谢

问题是视图元素在 angular 调用ngAfterViewInit生命周期钩子之前没有定义。

@ViewChild('my-el', { static: false })
public el: ElementRef<any> | undefined;

public ngOnInit(): void {
   console.log(this.el); // always undefined
}

    @ViewChild('my-el', { static: false })
    public el: ElementRef<any> | undefined;

    public ngAfterViewInit(): void {
       // If an element was found by @ViewChild(), it will be defined here
       // it could stil be undefined if no element was found.
       console.log(this.el);
    }

暂无
暂无

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

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