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

}

相关内容

热门资讯

透视了解!pokemmo内置修... 透视了解!pokemmo内置修改器,大菠萝789辅助器下载-果然是真的有辅助教程(哔哩哔哩)1、这是...
透视分享!wpk辅助器,wpk... 透视分享!wpk辅助器,wpk辅助器-其实有辅助软件(哔哩哔哩)1、玩家可以在线上大神俱乐部对游戏的...
透视关于!德普之星透视,德普之... 透视关于!德普之星透视,德普之星透视软件免费入口官网-好像是有辅助app(哔哩哔哩)1、起透看视 辅...
透视开挂!xpoker辅助助手... 透视开挂!xpoker辅助助手,pokemmo脚本辅助下载-原来一直总是有辅助神器(哔哩哔哩)1、下...
透视解谜!wpk俱乐部怎么作弊... 透视解谜!wpk俱乐部怎么作弊,wpk官网下载链接-好像一直都是有辅助插件(哔哩哔哩)1、该软件可以...
透视详细!aapoker透视脚... 透视详细!aapoker透视脚本下载,aapoker透视脚本下载-都是有辅助方法(哔哩哔哩)1、上手...
透视关于!wepoker透视有... 透视关于!wepoker透视有没有,wepoker透视脚本下载-好像真的是有辅助方法(哔哩哔哩)1、...
透视有挂!wepoker手机插... 透视有挂!wepoker手机插件,wejoker开挂-竟然是有辅助app(哔哩哔哩)1、首先打开辅助...
透视解迷!aapoker ai... 透视解迷!aapoker ai插件,aapoker辅助怎么用-本来是真的有辅助神器(哔哩哔哩)1、游...
透视必备!aapoker安装包... 透视必备!aapoker安装包怎么使用,aapoker脚本怎么用-确实真的有辅助方法(哔哩哔哩)1、...