Angular2 - Focusing a textbox on component load

前端 未结 10 1550
刺人心
刺人心 2020-12-02 16:29

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

10条回答
  •  佛祖请我去吃肉
    2020-12-02 17:01

    This answer is inspired by post Angular 2: Focus on newly added input element

    Steps to set the focus on Html element in Angular2

    1. Import ViewChildren in your Component

      import { Input, Output, AfterContentInit, ContentChild,AfterViewInit, ViewChild, ViewChildren } from 'angular2/core';
      
    2. Declare local template variable name for the html for which you want to set the focus

    3. Implement the function ngAfterViewInit() or other appropriate life cycle hooks
    4. Following is the piece of code which I used for setting the focus

      ngAfterViewInit() {vc.first.nativeElement.focus()}
      
    5. 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();
        }
      
     }

提交回复
热议问题