角度2焦点形式元素

Sna*_*ake 5 focus angular2-forms angular

我创建了一个带有角度2的表单,现在我想添加一些表单验证.验证工作正常,但现在我想专注于表单元素.这是否有可能在角度2.我到目前为止发现的是我可以使用elementRef和Renderer关注一个元素,即

this.renderer.invokeElementMethod(this.el.nativeElement, 'focus');
Run Code Online (Sandbox Code Playgroud)

但我不想通过elementRef访问该元素,而是想将焦点设置为我的FormGroup对象中的一个AbstractControl.即

this.form.controls[ controlIndex ].focus
Run Code Online (Sandbox Code Playgroud)

有角度2可能吗?如果不是,我如何将焦点设置为表单控件?

Rey*_*raa -2

一种方法是创建一个指令并将this.form.controls[ controlIndex ].hasError其作为参数传递给它:

@Directive({
    selector: '[focus-on-error]'
})
export class FocusOnErrorDirective implements AfterViewInit {
    constructor(public element: ElementRef) {}
    @Input('focusOnError') focusOnError;

    ngAfterViewInit() {
        // put all your focusing logic here
        // watches are also available here
        element.focus()
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的表单元素上您可以使用它:

<input type="text" focus-on-error="form.controls[ controlIndex ].hasError">
Run Code Online (Sandbox Code Playgroud)