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
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:
(keyup.enter) event is used to detect when the ngFor is used to repeat the input element for each word from the array of wordslast is a Boolean bound to a local variable which is true when the input is the last onelast ? addNewWord() : 0. This ensures that a new input field is only added when the Demo Plnkr