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

}

相关内容

热门资讯

推出新举措!WePoKer辅助... 推出新举措!WePoKer辅助器,pokerworld破解版下载(透视)科普教程(有挂助手)-哔哩哔...
截至目前!pokemmo手机版... 截至目前!pokemmo手机版脚本免费,wepoker分析(透视)揭露教程(有挂技术)-哔哩哔哩;运...
针对!红龙poker有辅助吗,... 针对!红龙poker有辅助吗,wepoker透视脚本安卓(透视)教你教程(存在有挂)-哔哩哔哩1、许...
据目击者称!wepoker怎么... 据目击者称!wepoker怎么破解游戏,wepoker软件靠谱么(透视)必备教程(有挂规律)-哔哩哔...
透视有挂!hhpoker德州挂... 透视有挂!hhpoker德州挂真的有吗,wepoker数据分析工具(透视)推荐教程(有挂存在)-哔哩...
透视规律!wpk安卓下载辅助,... 透视规律!wpk安卓下载辅助,拱趴大菠萝有挂吗(透视)有挂教程(真实有挂)-哔哩哔哩1、透视规律!w...
透视安卓版!wepoker私人... 透视安卓版!wepoker私人局外卦,拱趴大菠萝开挂方法(透视)透视教程(有挂辅助)-哔哩哔哩运拱趴...
据公告内容!hhpoker的辅... 据公告内容!hhpoker的辅助是真的吗,哈糖大菠萝破解器(透视)详细教程(讲解有挂)-哔哩哔哩1、...
透视规律!大菠萝789辅助器下... 透视规律!大菠萝789辅助器下载,hhpoker德州辅助(透视)开挂教程(真实有挂)-哔哩哔哩1、很...
据文件显示!wepoker透视... 据文件显示!wepoker透视脚本苹果版,如何下载wpk透视版(透视)详细教程(有挂方法)-哔哩哔哩...