![](/img/trans.png)
[英]Angular Material reactive form: showing different error messages for every validator
[英]What is the best way to handle the Angular material reactive form error messages?
在我們的項目中,我們使用的是 Angular 材質形式。 來到驗證
<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Email</mat-label>
<input matInput [formControl]="emailFormControl"
placeholder="Ex. pat@example.com">
<mat-hint>Errors appear instantly!</mat-hint>
<mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
Please enter a valid email address
</mat-error>
<mat-error *ngIf="emailFormControl.hasError('required')">
Email is <strong>required</strong>
</mat-error>
</mat-form-field>
</form>
Angular 材質組件默認會自動檢查該字段是否已被觸摸/提交驗證狀態。 並將無效的紅色應用於字段和錯誤消息。 不需要做任何事情。
一般文檔建議上述方法。 但不是直接在 html 中寫入錯誤消息並減少行數,我們通過這樣的服務傳遞它。 但這不是直接從 html 調用函數或服務的最佳實踐。
<mat-form-field class="example-full-width">
<mat-label>Email</mat-label>
<input matInput formControlName="emailFormControl"
placeholder="Ex. pat@example.com">
<mat-error>
<span [innerHTML]="commonService.getErrorMessages('emailFormControl',exampleForm )"></span>
<br>
<span [innerHTML]="getErrorMessages('emailFormControl',exampleForm )"></span>
</mat-error>
</mat-form-field>
我知道在 html 思想組件或服務中調用函數來綁定數據會根據更改檢測影響性能。
檢查以下鏈接以供參考示例材料反應形式
那么什么是替代和最佳方法?
mat-error
元素由MatFormField
管理,因此除非您有多個元素, MatFormField
不需要顯式顯示/隱藏它們。 最重要的是,錯誤總是由某種更改觸發,因此您可以訂閱表單對象的狀態和值更改並根據需要設置錯誤消息,僅使用一個mat-error
。 例如:
<mat-error>{{emailErrorMsg}}</mat-error>
...
emailErrorMsg: string = '';
...
ngOnInit() {
...
this.exampleForm.statusChanges.subscribe(() => this.setErrors());
}
setErrors() {
if (exampleForm.controls['emailFormControl'].hasError('required')) {
this.emailErrorMsg = "Email is required";
}
else if (exampleForm.controls['emailFormControl'].hasError('email')) {
this.emailErrorMsg = "Please enter a valid email address";
}
};
除了可以在沒有任何值或狀態更改的情況下觸發的“必需”之外,這很有效。 在這些情況下,可以在輸入上使用blur
偵聽器:
<input (blur)="setErrors()">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.