首页 > 解决方案 > 如何聚焦使用 Angular 模型驱动表单动态创建的输入字段

问题描述

我在 Angular 7 应用程序中使用模型驱动表单,其中一个允许用户动态添加/删除一组字段。这是我的意思的视觉参考:

在此处输入图像描述

这是我使用的 FormModel:

this.formModel = new FormGroup( {
    id : new FormControl(''),   
    name : new FormControl('', Validators.required), 
    comment : new FormControl(''),
    options : new FormControl(3), 
    domain_users: new FormArray([this.createDomainUser()])
    });

动态属性是domain_users,它是一个FormArray3 FormGroupFormControl域、用户名和密码)。当用户单击添加按钮时,这就是我所做的:

let du = this.formModel.get('domain_users') as FormArray;

if(nodes) {
  nodes.push(this.createDomainUser());
}

我希望,当用户单击添加按钮时,焦点将移动到新创建行的“域”字段。这样做的一个好的“角度方式”是什么?

提前致谢,

标签: angularformsangular7model-driven

解决方案


这是我找到的解决方案:

在 HTML 模板中:

<div class="ui-grid-row"
   *ngFor="let node of getDomainUsers().controls; let i = index" 
   [formGroupName]="i"
   #nodeInput>

在组件源中:

@ViewChildren('nodeInput') nodeInputs: QueryList<ElementRef>;

[...]
nodeAdd() {
  [...]

  try {
    // Try to get the first input element of the last row added
    let lastInput: HTMLInputElement = this.nodeInputs.last.nativeElement.children[0].children[0];

    lastInput.focus();
  }
  catch(e) {
    // Couldn't access the input element
  }  
}

推荐阅读