如果表单中的错误计数大于1,我想有条件地应用css类。如何在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>
如果我要在表单错误计数大于1的情况下将
form-error
类应用到<form>
,该怎么办?感谢您的想法。 最佳答案
我不知道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;
}