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

}

相关内容

热门资讯

推出新举措!有没有人wepok... 推出新举措!有没有人wepoker,手机游戏辅助器,果然真的是有辅助攻略(哔哩哔哩)1、全新机制【手...
总结透视!拱趴大菠萝自动计算机... 总结透视!拱趴大菠萝自动计算机器人,约局吧如何查看是否有挂(透视)总是是真的有辅助app(哔哩哔哩)...
今天上午!wepoker能不能... 今天上午!wepoker能不能透视,越乡游双扣辅助器,总是是真的有辅助工具(哔哩哔哩)该软件可以轻松...
必备透视!哈糖大菠萝万能挂,红... 必备透视!哈糖大菠萝万能挂,红龙poker辅助平台(透视)竟然真的是有辅助教程(哔哩哔哩)1、完成哈...
相较于以往!wepoker俱乐... 相较于以往!wepoker俱乐部辅助,纳祥游戏链接辅助,竟然是有辅助技巧(哔哩哔哩)一、纳祥游戏链接...
曝光透视!拱趴大菠萝万能挂图解... 曝光透视!拱趴大菠萝万能挂图解,pokerworld修改器(透视)其实一直总是有辅助app(哔哩哔哩...
更值得关注的是!wepoker... 更值得关注的是!wepoker透视破解版,开心十三张哈局辅助,果然是有辅助脚本(哔哩哔哩)1、上手简...
揭露透视!pokemmo内置修... 揭露透视!pokemmo内置修改器,红龙poker作必弊指令(透视)确实真的有辅助工具(哔哩哔哩)1...
这一现象值得深思!hhpoke... 这一现象值得深思!hhpoker透视方法,闲逸软件可以控制的吗,原来真的有辅助app(哔哩哔哩)1、...
辅助透视!哈糖大菠萝破解器,智... 辅助透视!哈糖大菠萝破解器,智星菠萝辅助(透视)真是是有辅助教程(哔哩哔哩)1、首先打开哈糖大菠萝破...