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游戏下载,pokemmo脚本,资料教程(有挂方法)1、在wepoker游戏...
四分钟辅助!约局吧开挂神器是真... 四分钟辅助!约局吧开挂神器是真的吗,哈糖大菠萝开挂,教材教程(揭秘有挂)1)约局吧开挂神器是真的吗辅...
8分钟辅助!wpk辅助器,wp... 8分钟辅助!wpk辅助器,wpk可以作弊吗,法子教程(有挂助手)1、让任何用户在无需wpk可以作弊吗...
9分钟辅助!aapoker如何... 9分钟辅助!aapoker如何设置胜率,aapoker破解侠是真的吗,指引教程(有挂教学)1、aap...
1分钟辅助!wejoker黑侠... 1分钟辅助!wejoker黑侠辅助器,wepoker软件安装包,讲义教程(新版有挂)1、全新机制【w...
六分钟辅助!来玩德州破解器,s... 六分钟辅助!来玩德州破解器,sohoo poker辅助,步骤教程(有挂方法)1、操作简单,无需来玩德...
4分钟辅助!德州圈脚本,wep... 4分钟辅助!德州圈脚本,wepoker透视功能下载,学习教程(竟然有挂)1、操作简单,无需wepok...
6分钟辅助!wepoker插件... 6分钟辅助!wepoker插件程序激活码,wepoker透视脚本免费app,窍门教程(有挂解密)1、...
五分钟辅助!aapoker能控... 五分钟辅助!aapoker能控制牌吗,hhpoker透视脚本,学习教程(有挂方针)1、玩家可以在aa...
三分钟辅助!智星菠萝可以辅助吗... 三分钟辅助!智星菠萝可以辅助吗,德州真人透视脚本,绝活儿教程(有挂方法)三分钟辅助!智星菠萝可以辅助...