I am developing a component in Angular2 (Beta 8). The component has a textbox and a dropdown. I would like to set the focus in textbox as soon as component is loaded or on c
This answer is inspired by post Angular 2: Focus on newly added input element
Steps to set the focus on Html element in Angular2
Import ViewChildren in your Component
import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
Declare local template variable name for the html for which you want to set the focus
Following is the piece of code which I used for setting the focus
ngAfterViewInit() {vc.first.nativeElement.focus()}
Add #input attribute to the DOM element you want to access.
///This is typescript
import {Component, Input, Output, AfterContentInit, ContentChild,
AfterViewChecked, AfterViewInit, ViewChild,ViewChildren} from 'angular2/core';
export class AppComponent implements AfterViewInit,AfterViewChecked {
@ViewChildren('input') vc;
ngAfterViewInit() {
this.vc.first.nativeElement.focus();
}
}