Reputation: 269
I have loop ngFor and i need to declare reference id '#' with the index .For eg
<button (click)="addRow()"></button>
<tr *ngFor="let data of datas; let i= index">
<td><ng-select #data{{i}} ></ng-select></td>
</tr>
addRow(){
// after selected data next row to focus.
}
and i want to focus to next row of ng-select.
Upvotes: 1
Views: 2641
Reputation: 57971
Update Viewchildren a input or a ng-select
with a input you can use ViewChildren
<div *ngFor="let item of items">
<input #data/>
</div>
@ViewChildren('data') data: QueryList<ElementRef>;
ngAfterViewInit()
{
this.data.changes.subscribe(()=>{
this.data.last.nativeElement.focus();
})
}
If we has a ng-select you need
<div *ngFor="let item of items">
<ng-select #data .....>
</ng-select>
</div>
<!--see that the "QueryList" is a NgSelectComponent-->
@ViewChildren('data') data: QueryList<NgSelectComponent>;
ngAfterViewInit()
{
this.data.changes.subscribe(()=>{
<!--we use filterInput.nativeElement-->
this.data.last.filterInput.nativeElement.focus();
})
}
A full stackblitz (In the stackblitz I add a "takeWhile" to unsubscribe changes in a ngOnDestroy the element)
Upvotes: 2
Reputation: 3934
Try to use the following code
<tr *ngFor="let dataObject of data; let i = index; trackBy:i;">
<td><ng-select #data{{i}} ></ng-select></td>
</tr>
For Focusing
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
...
@ViewChild('data1') inputEl:ElementRef;
addRow() {
setTimeout(() => this.inputEl.nativeElement.focus());
}
Or
import Renderer2 from @angular/core into your component. Then:
const element = this.renderer.selectRootElement('#data1');
setTimeout(() => element.focus(), 0);
Referrence https://coderanch.com/t/675897/languages/programmatically-manage-focus-Angular-app
Upvotes: 0