如果引发md-error,请关注FormControl

Roe*_*oel 7 angular-material2 angular

有时我们正在创建具有许多输入控件的表单,这些控件使容器(例如div)能够显示垂直滚动条.

我将此表单定义为a,FormGroup并且每个输入都FormControl包含一个md-error模板.

如果在提交表单时触发了md-error ,则可以滚动并聚焦表单控件?

Rah*_*ngh 1

您可以尝试使用 Directive 进行相同的操作并将其放置在 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(); 
        } 
    }

}
Run Code Online (Sandbox Code Playgroud)