如何在Angular中的文本框上设置焦点

时间:2017-03-30 10:14:53

标签: angular

如何将焦点设置在组件模板中的元素(如文本框)上?我试过以下代码。

HTML:

<input #input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

组件:

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();
    }

但是它给出了一个错误。

1 个答案:

答案 0 :(得分:2)

尝试使用ElementRef,测试并使用Angular 4.0.1:

import { ElementRef } from '@angular/core';

@ViewChild('input') vc: ElementRef;

ngAfterViewInit() {
   this.vc.nativeElement.focus();
}

DEMO