要在Angular中的FormArray的特定FormControl中设置焦点,可以使用ViewChild和ElementRef来获取FormControl对应的DOM元素,并使用focus()方法设置焦点。
以下是一个示例代码:
在组件模板中,定义一个FormArray,并在每个FormControl上应用一个模版引用变量:
在组件类中,使用ViewChild和ElementRef来获取FormControl对应的DOM元素,并在需要设置焦点时调用focus()方法:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: 'my-component.component.html',
styleUrls: ['my-component.component.css']
})
export class MyComponent implements OnInit {
myForm: FormGroup;
@ViewChild('inputRef') inputRef: ElementRef;
constructor() { }
ngOnInit() {
this.myForm = new FormGroup({
formArray: new FormArray([
new FormControl(''),
new FormControl(''),
new FormControl('')
])
});
}
setFocus(index: number) {
const control = this.myForm.get('formArray').controls[index];
control.markAsTouched(); // 设置为已触摸,以显示错误消息(如果有)
this.inputRef.nativeElement.focus();
}
}
在这个示例中,我们使用了模版引用变量#inputRef来获取FormControl对应的input元素的引用。然后,我们在setFocus方法中使用ViewChild来获取这个引用,并通过nativeElement属性访问原生DOM元素。最后,我们调用focus()方法来设置焦点。
你可以在需要的地方调用setFocus方法,以设置相应FormControl的焦点。