【发布时间】:2018-11-04 12:52:40
【问题描述】:
我正在尝试获取 Angular 指令来控制以编程方式将焦点设置在元素上。
这是我的指令在组件 html 中的样子:
<input type="text" class="form-control"
[(ngModel)]="inputText" [myFocus]="isFocused">
这是我的指令的样子:
import { Directive, OnInit, ElementRef, Renderer2, Input } from '@angular/core';
@Directive({
selector: '[myFocus]'
})
export class FocusDirective implements OnInit {
@Input('myFocus') isFocused: boolean;
constructor(private hostElement: ElementRef, private renderer: Renderer2) { }
ngOnInit() {
if(this.isFocused) {
this.renderer.selectRootElement(this.hostElement.nativeElement).focus();
}
}
}
然后在组件代码中我改变了这个:
this.isFocused = true;
指令包含在 app.module.ts 中,如下所示:
import { FocusDirective } from './directives/focus.directive';
@NgModule({
declarations: [
FocusDirective
],
bootstrap: [AppComponent]
})
export class AppModule { }
但是,当我这样做时,似乎没有设置焦点。 我知道 Renderer2 的工作方式发生了一些相当大的变化,我认为我在 ngOnInit() 方法中设置焦点的步骤有问题。
【问题讨论】: