Focus on newly added input element

前端 未结 5 1530
臣服心动
臣服心动 2020-11-22 15:28

I have a new Angular 2 app with a list of input boxes. When the user hits the return key, I add a new input box immediately after the one they\'re

5条回答
  •  甜味超标
    2020-11-22 16:08

    You can implement a simple input text directive, so that whenever a new input is created, it will auto focus itself. The focus() method is called inside of the ngAfterViewInit() component lifecycle hook after the view is fully initialized.

    @Directive({
        selector: 'input[type=text]'
    })
    export class FocusInput implements AfterViewInit {
        private firstTime: bool = true;
        constructor(public elem: ElementRef) {
        }
    
        ngAfterViewInit() {
          if (this.firstTime) {
            this.elem.nativeElement.focus();
            this.firstTime = false;
          }
        }
    }
    

    Use the FocusInput directive in your component:

    @Component({
        selector: 'app',
        directives: [FocusInput],
        template: `{{words |json}}`
    })
    export class AppComponent {
        words: Word[] = [];
        constructor() {
            this.addNewWord();
        }
        addNewWord() {
            this.words.push(new Word());
        }
    }
    

    Note the following:

    1. The (keyup.enter) event is used to detect when the key is pressed
    2. ngFor is used to repeat the input element for each word from the array of words
    3. last is a Boolean bound to a local variable which is true when the input is the last one
    4. The keyup event is bound to the expression last ? addNewWord() : 0. This ensures that a new input field is only added when the key is pressed from the last Input

    Demo Plnkr

提交回复
热议问题