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好友助力码,微乐家乡官方app,教程书教程(有挂分享)-哔哩哔哩1)wepo...
开挂透视!智星德州插件最新版本... 开挂透视!智星德州插件最新版本更新内容详解,万能透视辅助器免费版,诀窍教程(确实有挂)-哔哩哔哩1、...
解密透视!菠萝德普辅助器免费版... 解密透视!菠萝德普辅助器免费版在哪里,微乐游戏公众号辅助器,操作教程(有挂讲解)-哔哩哔哩1、完成菠...
揭露透视!pokemmo内置修... 揭露透视!pokemmo内置修改器,微乐麻将自建房app,妙计教程(有挂实锤)-哔哩哔哩暗藏猫腻,小...
揭露透视!wepoker有辅助... 揭露透视!wepoker有辅助吗,微乐山西威信小程序,攻略教程(有挂规律)-哔哩哔哩1.wepoke...
开挂透视!aapoker能控制... 开挂透视!aapoker能控制牌吗,微乐自建房免费黑科技推荐,绝活儿教程(有挂分析)-哔哩哔哩1、a...
了解透视!pokemmo修改器... 您好,pokemmo修改器手机版这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
分享透视!约局吧德州真的存在透... 分享透视!约局吧德州真的存在透视吗,微乐麻将脚本掌上程序,指引教程(有挂秘籍)-哔哩哔哩1、下载好约...
推荐透视!德普之星透视辅助,小... 推荐透视!德普之星透视辅助,小程序微乐陕西挖坑辅助器,练习教程(有挂辅助)-哔哩哔哩1、德普之星透视...
有挂透视!wepoker作弊方... 有挂透视!wepoker作弊方法,微乐麻将脚本掌上程序,教材教程(有挂讲解)-哔哩哔哩运wepoke...