角度自定义焦点指令。重点关注表单的第一个无效输入

时间:2019-06-10 11:46:56

标签: javascript angular angular-reactive-forms angular-forms angular-validation

我创建了一个指令以使输入无效(如果输入无效)

import { Directive, Input, Renderer2, ElementRef, OnChanges } from '@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[focusOnError]'
})
export class HighlightDirective implements OnChanges {
  @Input() submitted: string;

  constructor(private renderer: Renderer2, private el: ElementRef) { }

  ngOnChanges(): void {
    const el = this.renderer.selectRootElement(this.el.nativeElement);
    if (this.submitted && el && el.classList.contains('ng-invalid') && el.focus) {
      setTimeout(() => el.focus());
    }
  }

}

我确实有一个带有两个输入的反应形式,并且我已将该指令应用于两个输入

<form>
  ...
  <input type="text" id="familyName" focusOnError />
  ...
  <input type="text" id="appointmentCode" focusOnError />
  ...
</form>

提交表单后,它可以正常工作,但是我正在努力实现以下目标:

预期结果: -如果两个输入均无效,则在提交表单后,仅应集中第一个输入。

当前结果: -如果两个输入均无效,则在提交表单后,第二个输入将成为焦点。

我不知道如何指定“只有在第一个孩子的情况下才这样做”,我尝试使用指令的选择器没有运气。

有什么想法吗?

非常感谢。

2 个答案:

答案 0 :(得分:1)

好吧,只是为了搞笑 stackblitz。如果我们有一个formControl,我们可以注入ngControl,它就是控件本身。这样我们就可以获得formGroup。我控制“提交”在app.component中进行变通。

<button (click)="check()">click</button>

  check() {
    this.submited = false;
    setTimeout(() => {
      this.submited = true;
    })
  }

指令就像

export class FocusOnErrorDirective implements OnInit {
  @HostListener('input')
  onInput() {
    this._submited = false;
  }

  //I used "set" to avoid ngChanges, but then I need the "ugly" work-around in app.component
  @Input('focusOnError')
  set submited(value) {
    this._submited = value;
    if (this._submited) {  ((is submited is true
      if (this.control && this.control.invalid) { //if the control is invalid
        if (this.form) {
          for (let key of this.keys)  //I loop over all the
          {                           //controls ordered
            if (this.form.get(key).invalid) {  //If I find one invalid
              if (key == this.control.name) {  //If it's the own control
                setTimeout(() => {
                  this.el.nativeElement.focus()   //focus
                });
              }
              break;                           //end of loop
            }
          }
        }
        else
          this.el.nativeElement.focus()
      }
    }
  }
  private form: FormGroup;
  private _submited: boolean;
  private keys: string[];

  constructor(@Optional() private control: NgControl,  private el: ElementRef) {  }

  ngOnInit() {
    //in this.form we has the formGroup.
    this.form = this.control?this.control.control.parent as FormGroup:null;
    //we need store the names of the control in an array "keys"
    if (this.form)
    this.keys = JSON.stringify(this.form.value)
      .replace(/[&\/\\#+()$~%.'"*?<>{}]/g, '')
      .split(',')
      .map(x => x.split(':')[0]);
  }
}

答案 1 :(得分:1)

要控制Form的输入,我认为更好的解决方案是使用ViewChildren获取所有元素。因此,我们可以遍历这些元素,然后将焦点放在第一个。

因此,我们可以有一个辅助的简单指令:

@Directive({
  selector: '[focusOnError]'
})
export class FocusOnErrorDirective  {

  public get invalid()
  {
    return this.control?this.control.invalid:false;
  }
  public focus()
  {
     this.el.nativeElement.focus()
  }
  constructor(@Optional() private control: NgControl,  private el: ElementRef) {  }
}

而且,在我们的组件中,有一些类似

@ViewChildren(FocusOnErrorDirective) fields:QueryList<FocusOnErrorDirective>
check() {
    const fields=this.fields.toArray();
    for (let field of fields)
    {
      if (field.invalid)
      {
        field.focus();
        break;
      }
    }
  }

您可以在stackblitz

中查看实际情况

更新总是可以改善的地方:

为什么不创建适用于表格的指令?

@Directive({
  selector: '[focusOnError]'
})
export class FocusOnErrorDirective {

  @ContentChildren(NgControl) fields: QueryList<NgControl>

  @HostListener('submit')
  check() {
    const fields = this.fields.toArray();
    for (let field of fields) {
      if (field.invalid) {
        (field.valueAccessor as any)._elementRef.nativeElement.focus();
        break;
      }
    }
  }

所以,我们的.html就像

<form [formGroup]="myForm" focusOnError>
  <input type="text" formControlName="familyName" />
  <input type="text" formControlName="appointmentCode" />
  <button >click</button>
</form>

请参见stackblitz

更多,如果我们将其用作选择器表单

@Directive({
  selector: 'form'
})

即使我们可以删除表单中的focusOnError

<form [formGroup]="myForm" (submit)="submit(myForm)">
..
</form>

更新2 与formGroup和formGroup有关的问题。

NgControl仅考虑具有[(ngModel)],formControlName和[formControl]的控件。如果我们可以使用类似

的形式
myForm = new FormGroup({
    familyName: new FormControl('', Validators.required),
    appointmentCode: new FormControl('', Validators.required),
    group: new FormGroup({
      subfamilyName: new FormControl('', Validators.required),
      subappointmentCode: new FormControl('', Validators.required)
    })
  })

我们可以使用如下形式:

<form [formGroup]="myForm"  focusOnError (submit)="submit(myForm)">
  <input type="text" formControlName="familyName" />
  <input type="text" formControlName="appointmentCode" />
  <div >
    <input type="text" [formControl]="group.get('subfamilyName')" />
    <input type="text" [formControl]="group.get('subappointmentCode')" />
  </div>
  <button >click</button>
</form>

.ts中的哪里

get group()
  {
    return this.myForm.get('group')
  }
相关问题