I need to be able to switch focus to an input element when some event occurs. How do I do that in Angular 2?
For example:
Set focus - Angular 2/5
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-general',
templateUrl: './general.component.html',
styleUrls: ['./general.component.scss']
})
export class GeneralComponent {
@ViewChild("inputBox") _el: ElementRef;
setFocus() {
this._el.nativeElement.focus();
}
}
For setting focus on load
ngAfterViewInit() {
this._el.nativeElement.focus();
}
You can update this logic accordingly for key press.
More Info