Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus a FormControl if md-error is raised

Sometimes we are creating form that has many input controls which enable the container (e.g. div) to show a vertical scrollbar.

I define this form as a FormGroup and every input is a FormControl which has an md-error template incorporated.

It is possible to scroll and focus the form control if its md-error is triggered when submitting the form?

like image 824
Roel Avatar asked Sep 29 '17 10:09

Roel


1 Answers

You can try using a Directive for the same and place it on top 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(); 
        } 
    }

}
like image 137
Rahul Singh Avatar answered Nov 09 '22 01:11

Rahul Singh