Update (using renderer):
Note that the original Renderer service has now been deprecated in favor of Renderer2
as on Renderer2 official doc.
Furthermore, as pointed out by @GünterZöchbauer:
Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.
You can achieve this by using elementRef
as well as by ViewChild
. however it's not recommendable to use elementRef
due to:
as pointed out by official ng2 documentation.
elementRef
(Direct Access):export class MyComponent {
constructor (private _elementRef : ElementRef) {
this._elementRef.nativeElement.querySelector('textarea').focus();
}
}
ViewChild
(better approach):<textarea #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}"
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var
export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
renderer
:export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
constructor(private renderer: Renderer2){
}
ngAfterViewInit() {
//using selectRootElement instead of depreaced invokeElementMethod
this.renderer.selectRootElement(this.input["nativeElement"]).focus();
}
}