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 change event of dropdown. How would I achieve this in angular2. Following is Html for the component.
<div>
<form role="form" class="form-horizontal ">
<div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
<div class="form-group">
<label class="control-label col-md-1 col-sm-1" for="name">Name</label>
<div class="col-md-7 col-sm-7">
<input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />
</div>
<div class="col-md-2 col-sm-2">
<input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
</div>
</div>
</div>
<div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
<div class="form-group">
<label class="control-label col-md-1 col-sm-1" for="name">Person</label>
<div class="col-md-7 col-sm-7">
<select [(ngModel)]="SelectedPerson.Id" (change)="PersonSelected($event.target.value)" class="form-control">
<option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
</select>
</div>
</div>
</div>
</form>
</div>
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();
}
}
<div>
<form role="form" class="form-horizontal ">
<div [ngClass]="{showElement:IsEditMode, hidden:!IsEditMode}">
<div class="form-group">
<label class="control-label col-md-1 col-sm-1" for="name">Name</label>
<div class="col-md-7 col-sm-7">
<input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />
</div>
<div class="col-md-2 col-sm-2">
<input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />
</div>
</div>
</div>
<div [ngClass]="{showElement:!IsEditMode, hidden:IsEditMode}">
<div class="form-group">
<label class="control-label col-md-1 col-sm-1" for="name">Person</label>
<div class="col-md-7 col-sm-7">
<select [(ngModel)]="SelectedPerson.Id" (change)="PersonSelected($event.target.value)" class="form-control">
<option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
</select>
</div>
</div>
</div>
</form>
</div>