*有很多类似的问题,但我没有找到真正的重复,回答我的问题道歉,如果我错过了什么。
我有一个带有几个输入/按钮的页面(重复相同的组件),并且需要在按钮点击时关注正确的输入。
我尝试过了metaRef,nativeElement的变种,基于ID聚焦......但是我只能把它集中在DOM中的第一个或特定的......
<ng-template #myTemplate let-context="context">
<input #foo [id]="'myInput'+context.id" />
<button class="btn" [id]="'btnAction'+context.id (click)="focusOnInput()"></button>
</ng-template>
这在DOM中呈现如下:
<input #foo id="myInput1" />
<button class="btn" id="btnAction1></button>
<input #foo id="myInput2" />
<button class="btn" id="btnAction2></button>
<input #foo id="myInput3" />
<button class="btn" id="btnAction3></button>
这就是我一直在尝试的:
@ViewChild("foo") focusOnThis: ElementRef;
focusOnInput(): void {
this.focusOnThis.nativeElement.focus();
}
所需行为:单击按钮时,请关注相应的输入。目前,它只关注第一个,或我指定的任何ID ...
您可以在按钮单击处理程序中调用foo.focus()
。由于模板引用变量#foo
的范围是模板实例,因此它将引用兄弟输入元素。
<ng-template #myTemplate let-context="context">
<input #foo />
<button class="btn" (click)="foo.focus()"></button>
</ng-template>
有关演示,请参阅this stackblitz。
如果需要从方法设置焦点,请将foo
作为参数传递给它:
<ng-template #myTemplate let-context="context">
<input #foo />
<button class="btn" (click)="focusOnInput(foo)"></button>
</ng-template>
focusOnInput(input): void {
// Do something else here
...
input.focus();
}
如何使用带有id的数据属性并从中获取输入?
<ng-template #myTemplate let-context="context">
<input [attr.data-group]="context.id" />
<button class="btn" [attr.data-group]="context.id" (click)="focusOnInput($event)"></button>
</ng-template>
<input data-group="1" />
<button class="btn" data-group="1"></button>
<input data-group="2" />
<button class="btn" data-group="2"></button>
<input data-group="3" />
<button class="btn" data-group="3"></button>
// component constructor
constructor(
private readonly elementRef: ElementRef,
// ...
) {
// ...
}
focusOnInput(event: MouseEvent): void {
const groupId = (<HTMLElement>event.target).dataset.group;
const input = this.elementRef.nativeElement.querySelector(`input[data-group="${groupId}"]`);
input.focus();
}