user7751619
user7751619

Reputation:

How to set focus on a textbox in Angular

How can I set focus on an element (such as a textbox) in a component's template? I have tried the below code.

Html:

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

Component:

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

But it's giving an error.

Upvotes: 1

Views: 2344

Answers (1)

AVJT82
AVJT82

Reputation: 73337

Try using ElementRef, tested and working with Angular 4.0.1:

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

@ViewChild('input') vc: ElementRef;

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

DEMO

Upvotes: 2

Related Questions