角度2焦点形式元素

前端之家收集整理的这篇文章主要介绍了角度2焦点形式元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个带有角度2的表单,现在我想添加一些表单验证.验证工作正常,但现在我想专注于表单元素.这是否有可能在角度2.我到目前为止发现的是我可以使用elementRef和Renderer聚焦元素,即

this.renderer.invokeElementMethod(this.el.nativeElement,'focus');

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

this.form.controls[ controlIndex ].focus

有角度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()
    }
}

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

<input type="text" focus-on-error="form.controls[ controlIndex ].hasError">

猜你在找的Angularjs相关文章