【发布时间】:2020-01-06 17:39:57
【问题描述】:
我有一个带有许多动态生成输入的 GUI。
我可以像这样分配输入动态生成的 id:
<ul>
<li *ngFor="#item of items" >
<mat-form-field>
<input type=number attr.id={{item.name}}}
</mat-form-field>
</li>
</ul>
我希望能够将焦点设置在具有动态名称的特定输入上。这可能吗?
因为 id 是动态生成的,我们不能像这样使用 @viewchild 方法:
@ViewChild('usernameField') usernameField: ElementRef;
ngAfterViewInit() {
this.usernameField.nativeElement.focus();
}
材料文档中提到了焦点方法和 FocusOptions,但没有示例:
【问题讨论】:
-
如果 id 是在元素内部动态生成的,您可以使用 ViewChildren 并监听变化
-
不能只使用标准的 DOM 操作吗?
document.getElementById(myDynamicId).focus()?