可以通过使用 ViewChild 装饰器获取到动态创建的输入框所对应的 FormGroupDirective,然后在必要时通过调用 ElementRef 中的 focus() 方法即可将焦点设置到该输入框中。
示例代码:
在 .html 文件中,通过 ngFor 创建动态表单控件:
在 .ts 文件中,使用 ViewChild 装饰器获取动态创建的输入框所对应的 FormGroupDirective 并设置焦点:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({...})
export class MyComponent implements OnInit {
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
controls = ['firstName', 'lastName'];
form = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl()
});
constructor(private elem: ElementRef) {}
ngOnInit(): void {}
setFocus(input: HTMLInputElement): void {
this.formGroupDirective.form.patchValue({
[input.name]: input.value.trim()
});
this.elem.nativeElement.querySelector(`[formControlName="${input.name}"]`).focus();
}
}