2017-06-26 59 views
0

我想有條件地應用css類,如果在窗體中的錯誤計數大於1.我如何做到這一點在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. [email protected]) 
       </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> 

如果我想form-error應用類<form>如果形式的錯誤計數大於1,我該怎麼辦呢?感謝您的想法。

回答

2

我不知道Angular給你的這種方式。你必須在你的組件類中編寫自己的方法來計算它。您需要將每個控件中的錯誤數加起來。

事情是這樣的:

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; 
}