It is not recommended to access dom directly in Angular. Angular provides Renderer (Angular2) and Renderer 2(Angular4) abstractions.
Here is how to do in Angular 2:
@Component({
selector: 'my-app',
template: `
<div>
<input #inp id="myInput" type="text">
<button (click)="setFocus()">Set Focus</button>
</div>
`,
})
export class App {
@ViewChild('inp') inp:ElementRef;
constructor(private renderer: Renderer) {
}
setFocus() {
this.renderer.invokeElementMethod(this.inp.nativeElement, 'focus');
}
}
In Angular4 Renderer is depricated and Renderer2 is added. invokeElementMethod got removed and there is a discussion about it:
https://github.com/angular/angular/issues/13818#issuecomment-297815331
Here is Angular 4 way:
let onElement = this.renderer2.selectRootElement('#myInput');
onElement.focus();