Focus FormControl if md error is raised

Sometimes we create a form with many input controls that allow a container (like a div) to show a vertical scroll bar.

I define this form as FormGroup , and each input is a FormControl , which includes the md-error template.

Is it possible to scroll and focus a form control if its md error is triggered when a form is submitted?

+7
angular angular-material2
source share
1 answer

You can try using the directive to do this and place it on top of the form control.

 import { ElementRef, HostBinding, Input } from '@angular/core'; import { Directive } from '@angular/core'; @Directive({ selector: '[scrollToError]' }) export class ScrollDirective { constructor(private elRef:ElementRef) {} @HostBinding('hidden') isError:boolean = false; @Input() set scrollToError(cond) { this.isError = cond; if(cond) { this.elRef.nativeElement.scrollIntoView(); this.elRef.nativeElement.focus(); } } } 
+1
source share

All Articles