Issue
Now i know there are plenty of answers for this, trust me i am actually trying to figure it out but i can't get this feature to work on my app. I hope this question will not be defined as duplicate.
My question is how do i give focus to the last element of a ngFor when pressing a button?
I have a *ngFor
that i use to loop through some FormArray
like this:
<tr *ngFor="let reg of registrations.controls; let i = index" [formGroupName]="i">
<td>
<ng-select #peopleSelect [selectOnTab]="true" appendTo="body" placeholder="Select Operator"
formControlName="peopleId" style="width: 250px">
<ng-option *ngFor="let people of peopleList" [value]="people.peopleId">Name Surname</ng-option>
</ng-select>
</td>
</tr>
Here:
registrations
is a getter that gets aFormArray
and i loop through it's controlsng-select
is a select element ng-select#peopleSelect
is the ID given to a select element in the loop
In my ts file i do this:
@ViewChildren('peopleSelect') peopleSelectEl!: QueryList<ElementRef>;
addRow(): void { // method used in my app to add a row to the FormArray
this.peopleSelectEl.last.nativeElement.focus(); // here nativeElement is undefined
}
In the code above:
- using
this.peopleSelectEl.last.nativeElement.focus()
will get meundefined
- doing
console.log(this.peopleSelectEl.last)
will get me this: console.log
What am i doing wrong in my code? Why doing focus()
or even console logging .nativeElement
won't work?
UPDATE
console.log(this.peopleSelectEl)
gives this:
Don't know if this could help but i am trying to do all this inside a bootstrap modal... that i open from the parent component
Solution
Try like this
import { NgSelectComponent } from '@ng-select/ng-select';
@ViewChildren('select') peopleSelectEl!: QueryList<NgSelectComponent>;
ngAfterViewInit() {
this.peopleSelectEl.last.focus();
}
Answered By - cfprabhu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.