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辅助软件视频(透视)竟然真的有辅助插件(有挂方针)-哔哩哔哩wepoke...
无独有偶!wepoker私人局... 无独有偶!wepoker私人局辅助挂(透视)总是是有辅助工具(发现有挂)-哔哩哔哩1.wepoker...
透视好友房!pokernow辅... 透视好友房!pokernow辅助工具(透视)原来真的是有辅助app(有挂技术)-哔哩哔哩1、poke...
据通报!wepoker数据分析... 据通报!wepoker数据分析(透视)确实有辅助插件(有挂技术)-哔哩哔哩1、起透看视 wepoke...
今天上午!wepoker免费辅... 今天上午!wepoker免费辅助器(透视)一直真的有辅助下载(有挂规律)-哔哩哔哩1、下载好wepo...
透视ai代打!wepoker游... 透视ai代打!wepoker游戏下载(透视)一直是真的辅助安装(有挂秘诀)-哔哩哔哩透视ai代打!w...
今天下午!wepoker有没有... 今天下午!wepoker有没有机器人(透视)本来是真的辅助平台(有挂分析)-哔哩哔哩1、wepoke...
有了最新消息!aapoker公... 有了最新消息!aapoker公共底牌(透视)一直存在有辅助插件(有挂方针)-哔哩哔哩1、进入游戏-大...
透视实锤!德州局透视脚本免费版... 透视实锤!德州局透视脚本免费版下载手机版(透视)竟然真的有辅助插件(有挂方法)-哔哩哔哩一、德州局透...
透视私人局!uupoker透视... 透视私人局!uupoker透视(透视)一直真的有辅助工具(真是有挂)-哔哩哔哩1、首先打开uupok...