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开辅助... 您好,中至余干510k挂机这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
有消息称!wepokerplu... 有消息称!wepokerplus到底是挂了吗(透视)朋朋政和510k辅助(其实真的有辅助软件)-哔哩...
透视模拟器!德州局脚本(透视)... 透视模拟器!德州局脚本(透视)福建大玩家辅助操作视频(确实存在有辅助辅助器)-哔哩哔哩1、下载好福建...
经调查!hhpoker透视脚本... 经调查!hhpoker透视脚本下载(透视)熊猫互娱辅助(总是有辅助下载)-哔哩哔哩进入游戏-大厅左侧...
透视脚本!hhpoker视频巡... 透视脚本!hhpoker视频巡查真的假的(透视)创思维激k辅助器下载(果然真的有辅助安装)-哔哩哔哩...
透视插件!wepokerplu... 透视插件!wepokerplus开挂(透视)凑一桌游戏辅助器软件(竟然真的有辅助修改器)-哔哩哔哩一...
透视安装!佛手大菠萝辅助(透视... 透视安装!佛手大菠萝辅助(透视)吉安中至小程序(果然有辅助工具)-哔哩哔哩1、这是跨平台的佛手大菠萝...
透视科技!uupoker有透视... 透视科技!uupoker有透视吗(透视)闲逸软件安卓(一贯是真的辅助修改器)-哔哩哔哩1、很好的工具...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker手机版辅助(透视)情怀七喜游戏辅助(一直有辅助下载)-哔哩哔哩情怀七...
透视有挂!wepoker插件下... 透视有挂!wepoker插件下载(透视)小程序卡五星辅助(切实有辅助下载)-哔哩哔哩1、小程序卡五星...