[英]Angular Forms: How to avoid multiple NgIf divs for validation error messages?
我想簡化下面的代碼:
<div *ngIf="form1.errors?.checkDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
Date can't be in the future.
</div>
<div *ngIf="form1.errors?.notAfterDate && (form1.touched || form1.dirty)" class="cross-validation-error-message alert alert-danger">
Birth Date must be after 1/1/1800.
</div>
它應該只有1 div *ngif
並將錯誤消息作為值而不是硬編碼或使用ngFor
?
對此有任何幫助非常感謝。 謝謝。
管理多個Angular Form驗證消息的常用技術是將它們存儲在地圖中。
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' }
]
}
在模板中,使用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演示
我喜歡有一個錯誤組件。
@Component({
selector: 'app-error',
template: `
<small class="form-text text-danger" *ngIf="(control.touched || control.dirty)
&& control.invalid && (error?control.errors[error]:true)" >
<ng-content></ng-content>
</small>`
})
export class ErrorComponent {
@Input('controlName') controlName: string;
@Input('error') error: string
@Input('control') control:any
visible: boolean = false;
constructor(@Optional() @Host() public form: FormGroupDirective) { }
ngOnInit() {
if (this.form) {
this.control = this.form.form.get(this.controlName) as FormControl
}
}
}
您可以在formGroup中使用,使用controlName
輸入來指示控件,如果您有多個Validators並且想要區分,則使用error
輸入
<form [formGroup]="form">
<input formControlName="email">
<app-error controlName="email" error="required">Email required.</app-error>
<app-error controlName="email" error="email">incorrect email </app-error>
</form>
form=new FormGroup({
email:new FormControl('',[Validators.required,Validators.email])
})
或者是獨立的,使用[control]
輸入來指示控件
<input [formControl]="control">
<app-error [control]="control">control required</app-error>
control=new FormControl('',Validators.required)
請參閱stackblitz演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.