I\'ve many input boxes in a div and I need to focus one of them programmatically.
How to do it?
It\'s something like:
My approach would be to rely on a Directive and its selector, to remove the necessity of iterating over an array, and to avoid the local variables (I don't like the idea of having too many of them on my view), as Mark mentioned.
I'm assuming that the user always want only one and it's hardcoded, which is enough for the case the user asked about. Having a dynamic element to focus would defeat this approach.
The directive
@Directive({
selector : 'input[type=text][name=txt3]'
})
class Input {
constructor(public renderer: Renderer, public elementRef: ElementRef) {}
focusMe() {
this.renderer.invokeElementMethod(this.elementRef.nativeElement, 'focus', []);
}
}
The component would be basically the same in each answer
export class App {
@ViewChild(Input) input: Input;
selectSample() {
this.input.focusMe();
}
}
Here's the plnkr.