[英]Angular - Focus on input with dynamic IDs on click
*有很多類似的問題,但是我沒有找到一個真正的副本可以回答我的問題。
我的頁面上有幾個輸入/按鈕(重復了相同的組件),單擊按鈕時需要關注正確的輸入。
我已經嘗試了elementRef,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>
有關演示,請參見此堆疊閃電戰 。
如果需要通過方法設置焦點,請將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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.