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



我有以下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);
}

最新更新