我需要在組件初始化後設置特定輸入字段的焦點,並且希望完全選擇內部文本。 展望互聯網的一些提示,我最後寫一個speficic指令,是這樣的:Angular2控制焦點並以編程方式選擇
@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', []);
}
});
}}
在模板中,很明顯,我設定的指令的元素:
<input type="text" class="form-control" tabindex="1" [focusControl]="userIdFocus" maxlength="32">
接着,在組件的觀點被初始化,在AfterViewInit回調,我嘗試將焦點設置和選擇:
ngAfterViewInit() {
this.userIdFocus.emit(true);
}
的問題是該領域獲得焦點,但文本沒有被選中。如果我嘗試設置點擊按鈕後的焦點,那麼整個事情就會正確地工作。
我可以修復嗎?
要選擇在聚焦輸入控制的全部內容, 你試圖使用 我知道這不是Angular 2指令,但它不會解決您的問題嗎?注意「onClik」。 – meDev