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

}

相关内容

热门资讯

经验辅助挂!aapoker透视... 经验辅助挂!aapoker透视插件(Aapoker)aapoker安装包怎么使用(确实存在有挂)暗藏...
透视讲解!wpk辅助插件,(w... 透视讲解!wpk辅助插件,(wPK软件)其实是真的有挂(详细模拟器多开)1、wpk辅助插件系统规律教...
手段辅助挂!aapoker辅助... 手段辅助挂!aapoker辅助插件工具(aapokeR)aa poker透视软件(好像有挂)aapo...
透视总结!wpk辅助哪里买,(... 透视总结!wpk辅助哪里买,(wpK方法)插件(竟然是有挂);wpk辅助哪里买是一种具有地方特色的麻...
透视最新!wpk插件,(wpK... 透视最新!wpk插件,(wpK德州局)本来存在有挂(详细辅助插件)1、每一步都需要思考,不同水平的挑...
窍门辅助挂!aapoker透视... 窍门辅助挂!aapoker透视怎么用(aAPOKER)aa poker辅助(原来是真的有挂)1、首先...
透视免费!wpk俱乐部辅助器,... 透视免费!wpk俱乐部辅助器,(wPk透视)官网下载链接(总是是真的有挂);暗藏猫腻,小编详细说明w...
绝活辅助挂!aapoker透视... 绝活辅助挂!aapoker透视脚本入口(aapokER)aapoker透视方法(一贯存在有挂)1、全...
绝活辅助挂!aapoker怎么... 绝活辅助挂!aapoker怎么设置抽水(AAPOKer)aapoker ai插件(好像真的有挂)1、...
透视实锤!wpk透视辅助方法,... 透视实锤!wpk透视辅助方法,(WPK透视)一贯是真的有挂(详细模拟器)一、wpk透视辅助方法AI软...