Angular响应式表单中如何将焦点设置到动态创建的输入框?
创始人
2024-10-30 08:00:47
0

可以通过使用 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();
  }

}

相关内容

热门资讯

第二分钟辅助!智星德州辅助译码... 第二分钟辅助!智星德州辅助译码插件靠谱吗,福建大菠萝万能辅助器,手筋教程(有挂总结)1、智星德州辅助...
第三分钟辅助!we poker... 第三分钟辅助!we poker免费辅助器,佛手在线大菠萝智能辅助器,绝活教程(有挂猫腻)1、佛手在线...
4分钟辅助!wepoker底牌... 4分钟辅助!wepoker底牌透视,epoker底牌透视,经验教程(证实有挂)1、上手简单,内置详细...
第9分钟辅助!wepoker有... 第9分钟辅助!wepoker有脚本吗,wepoker轻量版透视方法,经验教程(真的有挂)1、每一步都...
第四分钟辅助!hhpoker德... 第四分钟辅助!hhpoker德州牛仔视频,hhpoker透视脚本视频,经验教程(有挂详情)1、hhp...
第4分钟辅助!wepoker一... 第4分钟辅助!wepoker一直输的号能继续打吗,wepoker怎么看牌型,策略教程(有挂细节)1、...
八分钟辅助!wepoker轻量... 八分钟辅助!wepoker轻量版透视系统,hhpoker辅助挂下载,法门教程(确实有挂)1、该软件可...
第2分钟辅助!werplan免... 第2分钟辅助!werplan免费挂下载,wepoker免费脚本,妙计教程(证实有挂)1)werpla...
五分钟辅助!哈糖大菠萝助手,h... 五分钟辅助!哈糖大菠萝助手,hhpoker软件安装包,教材教程(发现有挂)1、上手简单,内置详细流程...
第3分钟辅助!拱趴大菠萝作弊方... 第3分钟辅助!拱趴大菠萝作弊方法,xpoker辅助怎么用,手册教程(有挂透明挂)一、拱趴大菠萝作弊方...