我用angular 2创建了一个表单,现在我想添加一些表单验证。验证正在工作,但现在我想把重点放在表单元素上。这在角2中可能吗?到目前为止,我发现我可以用elementRef和Renderer(即
)来聚焦元素this.renderer.invokeElementMethod(this.el.nativeElement, 'focus');
但是我不想通过elementRef访问元素,相反,我想将焦点设置为FormGroup对象中的AbstractControl之一。即
this.form.controls[ controlIndex ].focus
对于角2,这可能吗?如果没有,我如何将焦点设置为窗体控件?
在Angular 8中的当前状态
使用ReactiveForm
仍然不可能做到这一点。为此,仍然有必要创建一个专门的指令。
import { Directive, HostListener, ElementRef } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { FormGroup } from '@angular/forms';
@Directive({
selector: '[focusInvalidInput]'
})
export class FormDirective {
constructor(private el: ElementRef) { }
@HostListener('submit')
onFormSubmit() {
const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
if (invalidControl) {
invalidControl.focus();
}
}
}
这样使用:
<form focusInvalidInput [formGroup]="form" (ngSubmit)="submit()">
<label for="first">First Name</label>
<input formControlName="first" id="first" />
<label for="last">Last Name</label>
<input formControlName="last" id="last" />
<br />
<button>submit</button>
</form>
演示:https://stackblitz.com/edit/angular-fesawc
一种方法是创建一个指令并将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">