Angular 2 焦点表单元素

5

我使用Angular 2创建了一个表单,现在我想要添加一些表单验证。验证正在工作,但现在我想集中到表单元素上。在Angular 2中是否有可能实现这个功能?目前我所发现的是可以使用ElementRef和Renderer来聚焦元素,例如:

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

但我不想通过elementRef访问元素,而是想将焦点设置在我的FormGroup对象中的一个AbstractControl上。也就是说:

this.form.controls[ controlIndex ].focus

这在Angular 2中是否可行?如果不行,我该如何将焦点设置到表单控件上?
2个回答

0

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

-2
一种方法是创建一个指令,并将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">

谢谢你的帮助,我今天会尝试你的方法。 - Snake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接