Angular,如何将焦点设置在 FormArray 的特定 FormControl 中

Ale*_*dro 6 angular

l如何将焦点设置到formArray中的特定字段?

这是数组形式:

    this.productForm = this.formBuilder.array([
     this.formBuilder.group({
     code: [null],
     description: [null],
     unitPrice: [null],
     qty: [null],
     discount: [null],
     vat: [null],
     total: [null],
     amount: [null],
     taxAmount: [null]
  })
]);
Run Code Online (Sandbox Code Playgroud)

我可以有很多这样的表单组,并且我需要关注特定的描述字段。角度有聪明的方法吗?

rrd*_*rrd 3

如果您知道要关注的特定项目,那么首先通过添加模板引用会相当简单:

<input
  #fieldName
  type="text"
  id="fieldName"
  name="fieldName"
  formControlName="yourFieldName" />
Run Code Online (Sandbox Code Playgroud)

然后在您的组件中(可能在 ngAfterViewInit() 方法中):

@ViewChild('fieldName') fieldName: ElementRef;
Run Code Online (Sandbox Code Playgroud)

然后专注于你的元素:

this.fieldName.nativeElement.focus();
Run Code Online (Sandbox Code Playgroud)

注意,这很容易受到 XSS 攻击