Angular 2 Focus Shape Element

I created a form with angular 2, and now I want to add some form validation. Validation works, but now I want to focus on the elements of the form. Is this possible in angular 2. What I have found so far is that I can focus the element with elements elementRef and Renderer ie

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

But I do not want to access the element through elementRef, instead I want to set the focus to one of my AbstractControl in my FormGroup object. i.e

this.form.controls[ controlIndex ].focus

is this possible with angular 2? If not, how to set focus on the form control?

+4
source share
1 answer

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">
-2

Source: https://habr.com/ru/post/1658685/


All Articles