【问题标题】:How to focus input field created dynamically using an Angular model driven form如何聚焦使用 Angular 模型驱动表单动态创建的输入字段
【发布时间】:2019-04-15 05:04:33
【问题描述】:

我在 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,它是FormGroupFormArray,带有3 个FormControl(域、用户名和密码)。当用户点击添加按钮时,我就是这样做的:

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

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

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

提前致谢,

【问题讨论】:

标签: angular forms angular7 model-driven


【解决方案1】:

这是我找到的解决方案:

在 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
  }  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多