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

}

相关内容

热门资讯

脚本揭幕!wpk透视怎么安装,... 脚本揭幕!wpk透视怎么安装,wpk德州局怎么透视(透视)本来真的有器(哔哩哔哩)1、完成德州局怎么...
脚本解迷!wepoker透视脚... 脚本解迷!wepoker透视脚本免费下载,wepoker看底牌(透视)都是是真的攻略(哔哩哔哩)1、...
脚本有挂!德普之星私人局辅助免... 脚本有挂!德普之星私人局辅助免费,德普之星有辅助软件吗(透视)真是存在有方法(哔哩哔哩)1、打开软件...
透视普及!wepoker辅助工... 透视普及!wepoker辅助工具,wepoker能不能透视(透视)一贯有挂(哔哩哔哩)1、辅助软件下...
脚本总结!德普之星透视软件免费... 脚本总结!德普之星透视软件免费入口官网,德普之星透视辅助软件是真的吗(透视)确实有教程(哔哩哔哩)辅...
透视普及!wepoker私人局... 透视普及!wepoker私人局透视教程,wejoker免费脚本(透视)总是真的是有app(哔哩哔哩)...
脚本教你!hhpoker德州透... 脚本教你!hhpoker德州透视挂,hhpoker辅助挂是真的吗(透视)真是存在有工具(哔哩哔哩)1...
透视总结!hhpoker怎么破... 透视总结!hhpoker怎么破解,hhpoker辅助软件是真的么(透视)总是真的有器(哔哩哔哩)一、...
透视有挂!aapoker辅助怎... 透视有挂!aapoker辅助怎么用,aapoker透视脚本入口(透视)真是有脚本(哔哩哔哩)1、首先...
脚本辅助!有没有人wepoke... 脚本辅助!有没有人wepoker,wepoker好友局透视(透视)其实是真的教程(哔哩哔哩)1、全新...