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:
For manipulation on DOM elements always try to use Directives. In this case you are able to write simple directive.
For accessing DOM from directive we can inject reference of our host DOM element by the ElementRef in directive constructor.
constructor(@Inject(ElementRef) private element: ElementRef) {}
For change detection of binded value we can use ngOnChanges livecycle method.
protected ngOnChanges() {}
All other stuff is simple.
// Simple 'focus' Directive
import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
selector: '[focus]'
})
class FocusDirective {
@Input()
focus:boolean;
constructor(@Inject(ElementRef) private element: ElementRef) {}
protected ngOnChanges() {
this.element.nativeElement.focus();
}
}
// Usage
@Component({
selector : 'app',
template : `
`,
directives: [FocusDirective]
})
export class App {
private inputFocused = false;
moveFocus() {
this.inputFocused = true;
// we need this because nothing will
// happens on next method call,
// ngOnChanges in directive is only called if value is changed,
// so we have to reset this value in async way,
// this is ugly but works
setTimeout(() => {this.inputFocused = false});
}
}
To solve the problem with setTimeout(() => {this.inputFocused = false}); We can bind our directive for events source - EventEmitter, or to Observable. Below is an example of EventEmitter usage.
// Directive
import {Directive, EventEmitter, Input, ElementRef} from 'angular2/core';
@Directive({
selector: '[focus]'
})
class FocusDirective {
private focusEmitterSubscription;
// Now we expect EventEmitter as binded value
@Input('focus')
set focus(focusEmitter: EventEmitter) {
if(this.focusEmitterSubscription) {
this.focusEmitterSubscription.unsubscribe();
}
this.focusEmitterSubscription = focusEmitter.subscribe(
(()=> this.element.nativeElement.focus()).bind(this))
}
constructor(@Inject(ElementRef) private element: ElementRef) {}
}
// Usage
@Component({
selector : 'app',
template : `
`,
directives: [FocusDirective]
})
class App {
private inputFocused = new EventEmitter();
moveFocus() {
this.inputFocused.emit(null);
}
}
Both solutions solves your problem, but second has a little better performance and looks nicer.