检查错误计数 Angular 反应形式

Check Error Count Angular Reactive Forms

如果表单中的错误计数大于 1,我想有条件地应用 css class。我如何在 angular4 中执行此操作?

组件:

import { Component } from "@angular/core";
import { FormGroup, ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';

@Component({
    ...
})

export class RegisterComponent {
  complexForm : FormGroup;

  constructor(fb: FormBuilder){
    this.complexForm = fb.group({
      'emailAddress' : [null, Validators.email],
      'firstName': [null, Validators.compose([Validators.required, Validators.minLength(2)])],
      ...
    })
  }

  submitForm(value: any){
    console.log(value);
  }
}

模板:

<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
      <section class="form-block">
          <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['emailAddress'].valid && complexForm.controls['emailAddress'].touched}">
                <label for="formFields_1">Email Address</label>
                <input [formControl]="complexForm.controls['emailAddress']" type="text" spellcheck="false" id="formFields_1" placeholder="" size="35">
                <span *ngIf="complexForm.controls['emailAddress'].hasError('email') && complexForm.controls['emailAddress'].touched" class="tooltip-content">
                    Please enter a valid email address (ex. joan@vmware.com)
                </span>
          </div>   
          <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['firstName'].valid && complexForm.controls['firstName'].touched}">
              <label for="formFields_2">First Name</label>
                <input [formControl]="complexForm.controls['firstName']" type="text" spellcheck="false" id="formFields_2" placeholder="" size="35">
                <span *ngIf="complexForm.controls['firstName'].hasError('required') && complexForm.controls['firstName'].touched" class="tooltip-content">
                    Your first name must contain at least one letter
                </span>
          </div>
     </section>
</form>

如果表单错误计数大于 1,我想将 class form-error 应用到 <form>,我该怎么做?谢谢你的想法。

我不知道 Angular 有什么方法可以给你这个。您必须在组件 class 中编写自己的方法来计算它。您需要将每个控件中的错误计数相加。

像这样:

getErrorCount(container: FormGroup): number {
    let errorCount = 0;
    for (let controlKey in container.controls) {
        if (container.controls.hasOwnProperty(controlKey)) {
            if (container.controls[controlKey].errors) {
                errorCount += Object.keys(container.controls[controlKey].errors).length;
                console.log(errorCount);
            }
        }
    }
    return errorCount;
}

有更好的解决方法。

Object.keys(formGroup.errors).length

这将 return 我们在 formGroup

中的错误总计数