我正在Angular2(Beta 8)开发一个组件.该组件有一个文本框和一个下拉列表.一旦组件加载或更改下拉列表事件,我想在焦点放在文本框中.如何在角度2中实现这一点.以下是组件的Html.
<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>
这个答案是灵感来自后
Angular 2: Focus on newly added input element
原文链接:/angularjs/143096.html在cornerjs2中设置Html元素的重点的步骤
>在您的组件中导入ViewChildren
import { Input,Output,AfterContentInit,ContentChild,AfterViewInit,ViewChild,ViewChildren } from 'angular2/core';
>为要设置焦点的html声明本地模板变量名.
>实现函数ngAfterViewInit()或其他适当的生命周期钩子.
>以下是我用于设置焦点的代码片段
ngAfterViewInit() {vc.first.nativeElement.focus()}
///This is typescript import {Component,Input,AfterViewChecked,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>