I updated your code with my answer.
You can see the full code here: https://stackblitz.com/edit/angular-gdajaw
Only thing I changed is (and I strongly recommend it) instead of timeout, I use ChangeDetectorRef to wait for angular change detection to run. After change detection you can select the added input to focus.
Here is the changed AppComponent
:
import { Component, Renderer2, ChangeDetectorRef } from '@angular/core';
import { Note } from './note.model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public notes: Note[] = [];
public newNote = new Note();
constructor(
protected renderer: Renderer2,
private cRef: ChangeDetectorRef
) { }
ngOnInit() {
this.notes.push(new Note({ content: 'foo' }));
this.notes.push(new Note({ content: 'bar' }));
}
newLine(note: string) {
// Switch it up
this.notes.push(new Note(this.newNote));
// Select our original element
// setTimeout(() => this.renderer.selectRootElement('#note'+(this.notes.length-1)).focus(), 0);
// use ChangeDetectorRef detectChanges method to wait for angular to go through change detection
this.cRef.detectChanges();
// after change detection you can select the added input to focus
this.renderer.selectRootElement('#note' + (this.notes.length - 1)).focus()
// Reset the new line
//this.newNote = new Note();
this.newNote = new Note({content: null});
}
}