angular - 如何聚焦使用 Angular 模型驱动表单动态创建的输入字段
问题描述
我在 Angular 7 应用程序中使用模型驱动表单,其中一个允许用户动态添加/删除一组字段。这是我的意思的视觉参考:
这是我使用的 FormModel:
this.formModel = new FormGroup( {
id : new FormControl(''),
name : new FormControl('', Validators.required),
comment : new FormControl(''),
options : new FormControl(3),
domain_users: new FormArray([this.createDomainUser()])
});
动态属性是domain_users
,它是一个FormArray
3 FormGroup
(FormControl
域、用户名和密码)。当用户单击添加按钮时,这就是我所做的:
let du = this.formModel.get('domain_users') as FormArray;
if(nodes) {
nodes.push(this.createDomainUser());
}
我希望,当用户单击添加按钮时,焦点将移动到新创建行的“域”字段。这样做的一个好的“角度方式”是什么?
提前致谢,
解决方案
这是我找到的解决方案:
在 HTML 模板中:
<div class="ui-grid-row"
*ngFor="let node of getDomainUsers().controls; let i = index"
[formGroupName]="i"
#nodeInput>
在组件源中:
@ViewChildren('nodeInput') nodeInputs: QueryList<ElementRef>;
[...]
nodeAdd() {
[...]
try {
// Try to get the first input element of the last row added
let lastInput: HTMLInputElement = this.nodeInputs.last.nativeElement.children[0].children[0];
lastInput.focus();
}
catch(e) {
// Couldn't access the input element
}
}
推荐阅读
- r - 计算 R 中每一天的对数差异 为每一天的第一次观察产生 NA
- javascript - iOS 13:全屏模式下的 webapp 在启动时不会刷新
- apache-spark - 出现“容器因超出内存限制而被 YARN 杀死”的异常情况。
- java - 由于 org.jboss.vfs.spi.JavaZipFileSystem 的实例数量更多而导致内存泄漏
- google-play - 使用 Fastlane 上传 Unreal 应用程序时出现“Release 不符合 Play 64 位要求”
- gitlab - 为什么我的 gitlab 管道因 rsync 错误而失败
- python - 二维数组和一维数组的点积不同于矩阵和一维数组
- regex - 如何在找到某个字符串后插入文本?
- sql - 如何使用 OPENQUERY 调用的链接数据库进行 INNER JOIN?
- javascript - 无法从 Json 对象中提取单个值,仅从 API 获取 [Object promise]