I need to set the focus of a specific input field after the component initialization, and I'd like to have the inside text fully selected. Looking on the internet for some hint, I ended up writing a speficic directive, this way:
@Directive({
selector: '[focusControl]'})
export class FocusDirective {
@Input('focusControl') focusEvent: EventEmitter<boolean>;
constructor( @Inject(ElementRef) private element: ElementRef, private renderer: Renderer) {
}
ngOnInit() {
this.focusEvent.subscribe(event => {
this.renderer.invokeElementMethod(this.element.nativeElement, 'focus', []);
if (this.element.nativeElement.tagName == "INPUT") {
this.renderer.invokeElementMethod(this.element.nativeElement, 'select', []);
}
});
}}
In the template, obviously I set the directive on the element:
<input type="text" class="form-control" tabindex="1" [focusControl]="userIdFocus" maxlength="32">
Then, after the component's views are initialized, in the AfterViewInit callback, I try to set focus and select:
ngAfterViewInit() {
this.userIdFocus.emit(true);
}
The problem is the field gets the focus, but the text is NOT selected. If I try to set the focus behind a click on a button, then the whole thing works corretcly.
I could I fix that?