Reputation: 793
I have a dynamic HTML list of elements, that all have a specific attribute (for example 'role=option').
I want to select the first element and give it focus. In angular 1, it was possible through:
angular.element(document.querySelector('[role="option"]')).focus()
In angular2, I can't find the equivalent way of doing this. All answers seem to involve viewChild and giving a specific #ref
to an element, but the HTML is created dynamically through *ngFor
, so every element would end up with the same #ref
in the loop.
How to do this?
Upvotes: 2
Views: 1626
Reputation: 31105
You could still use the template reference variable and use ViewChildren
and the first
property to focus on the first element in the QueryList
. Try the following
Template
<ng-container *ngFor="let item of items; let i=index">
<input #input (change)="templateRefVariable(input.value)"/>
<br />
</ng-container>
Controller
import { Component, TemplateRef, ViewChildren, QueryList, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
items = ['item1', 'item2', 'item3', 'item4'];
@ViewChildren('input') inputElems: QueryList<ElementRef>;
templateRefVariable(value) {
console.log(value);
}
ngAfterViewInit() {
this.inputElems.first.nativeElement.focus();
}
}
Working example: Stackblitz
Upvotes: 3