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();
  }

}

相关内容

热门资讯

大神推荐!哈糖大菠萝软件下载,... 大神推荐!哈糖大菠萝软件下载,we poker游戏下,总是是有挂(有挂细节)1、上手简单,内置详细流...
一分钟教你!aa poker辅... 一分钟教你!aa poker辅助包,pokeplus脚本,好像真的是有挂(有挂讲解);1、完成辅助器...
来一盘!wepoker的辅助器... 来一盘!wepoker的辅助器,wpk透视工作室,真是存在有挂(揭秘有挂)1、玩家可以在线上大神俱乐...
科技分享!pokermaste... 科技分享!pokermaster修改器,wepoker游戏安装教程,其实真的是有挂(有挂规律)1、操...
一分钟了解!德普之星辅助工具如... 一分钟了解!德普之星辅助工具如何打开,wepoker免费脚本,都是是真的有挂(有挂讲解);1、wep...
实测分享!wepokerplu... 实测分享!wepokerplus脚本,aapoker怎么选牌,原来真的是有挂(有挂教学)1、这是跨平...
玩家必备教程!hhpoker可... 玩家必备教程!hhpoker可以控制牌吗,德州局透视脚本,一直存在有挂(有挂技巧)1、让任何用户在无...
如何分辨真伪!wepoker有... 如何分辨真伪!wepoker有辅助吗,hhpoker是真的还是假的,竟然有挂(有挂解惑)1、任何透视...
避坑细节!wepoker透视a... 避坑细节!wepoker透视app下载,HH平台挂,果然是真的有挂(证实有挂)亲,关键说明,透视脚本...
重大通报!wejoker辅助器... 重大通报!wejoker辅助器要钱玩吗,wepoker挂,一直有挂(确实有挂)1、任何透视是真的假的...