管理多个 Angular 表单验证消息的常用技术是将它们存储在地图中。
public validationMessages = {
'firstName': [
{ type: 'required', message: 'First Name is required' },
{ type: 'maxlength', message: 'First Name may only contain 5 characters.' }
],
'lastName': [
{ type: 'required', message: 'Last Name is required' },
{ type: 'pattern', message: 'Last Name may not be "Smith".' }
],
'email': [
{ type: 'required', message: 'Email is required' },
{ type: 'email', message: 'Enter a valid email' }
]
}
HTML 模板
在模板中,用于NgFor
遍历所需表单控件的验证消息。
<label>
Email:
<input type="email" autocomplete="email" formControlName="email" required>
</label>
<!-- Validation Errors -->
<div *ngFor="let validation of validationMessages.email">
<div *ngIf="profileForm.get('email').hasError(validation.type) && (profileForm.get('email').dirty || profileForm.get('email').touched)">
<small style="color:red;">{{validation.message}}</small>
</div>
</div>
例子
看Stackblitz Demo