[英]How to get form control validation errors in template in Angular
我有一個表格,可以根據下拉菜單中的某些值更改其驗證。 如果選擇了大學A,則必須在60中選擇最小百分比,如果選擇了大學B,則最小百分比將降至55。盡管我已經找到了一種獲取模板中最小誤差的方法,所以我不必費勁在模板中編寫百分比值。 盡管我不確定這是否是正確的方法。
<div formGroupName="marks">
<div class="form-group">
<label for="email" class="col-lg-3 control-label">Semester 1</label>
<div class="col-lg-3">
<input autocomplete="off"
#sem1
type="text"
min="0"
max="99"
maxlength="1"
maxlength="2"
class="form-control"
id="email"
placeholder="Sem 1 (%)"
(keypress)="onlyNumberKey($event)"
formControlName="sem1">
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
registrationForm.controls['marks'].controls['sem1'].touched"
class="text-danger">
Sem 1 percentage required
</span>
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
registrationForm.controls['marks'].controls['sem1'].touched"
class="text-danger">
Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }} and above.
</span>
</div>
</div>
</div>
零件
registrationForm = new FormGroup({
college: new FormControl('', [
Validators.required, dropDrownValidator
]),
marks: new FormGroup({
sem1: new FormControl('',
[
Validators.required,
Validators.min(60),
Validators.max(99),
Validators.minLength(1),
Validators.maxLength(2)
]
)
})
});
嗯,值得一提的是,由於此問題 , min
和max
內置驗證器已在4.3.0-beta.0中回滾,並且不再(可能)在4.3.0 final中導出。 大概他們應該回到v5了。
話雖如此,我建議您或者自己做一個自定義驗證器,或者將min
驗證器從源代碼( @angular/forms
)復制到您的項目中,以防止將來發生中斷。
這是修改后的復制粘貼版本:
function customMin(min: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value == null || min == null) {
return null;
}
const value = parseFloat(control.value);
return isNaN(value) || value >= min ? null : {
customMin: { min, actual: control.value }
};
};
}
為了實現您想要的目標,您必須注意 college
控制方面的變化。
您可以使用模板中的 (change)
來執行此操作:
<select formControlName="college" (change)="myAwesomeFunction($event.target.value)">
...
</select>
甚至在component中使用valueChanges
:
this.registrationForm.get('college').valueChanges.subscribe(college => this.myAwesomeFunction(college));
在function
,根據大學用戶的選擇,您可以使用AbstractControl#setValidators
將最小值設置為驗證器,如下所示:
myAwesomeFunction() {
const min: number = college === 'CollegeA' ? 60 : 55;
const control: FormControl = this.registrationForm.get('marks.sem1');
control.setValidators([Validators.required, customMin(min)]);
control.updateValueAndValidity();
}
提示:
1-由於您使用的是模型驅動的表單,因此您不應該在HTML中進行驗證,保持其整潔並將所有內容都放入組件中。
2-您可以使用FormBuilder
來簡化form
的構造(請參見下面的PLUNKER)。
3-絕對不要這樣訪問私有屬性:
{{ registrationForm.get('marks.sem1')._errors.min.min
如果需要,只需使用errors
而不是_errors
即可。
4-您可以簡化標記:
代替:
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('required') &&
registrationForm.controls['marks'].controls['sem1'].touched"
class="text-danger">
Sem 1 percentage required
</span>
<span *ngIf="registrationForm.controls['marks'].controls['sem1'].hasError('min') ||
registrationForm.controls['marks'].controls['sem1'].hasError('max') ||
registrationForm.controls['marks'].controls['sem1'].hasError('minlength')||
registrationForm.controls['marks'].controls['sem1'].hasError('maxlength') &&
registrationForm.controls['marks'].controls['sem1'].touched"
class="text-danger">
Percenatge must be {{ registrationForm.get('marks.sem1')._errors.min.min }} and above.
</span>
你可以有:
<div class="text-danger" *ngIf="registrationForm.get('marks.sem1').touched">
<span *ngIf="registrationForm.hasError('required', 'marks.sem1')">
Sem 1 percentage required
</span>
<span *ngIf="registrationForm.getError('customMin', 'marks.sem1') as error">
Percentage must be greater than or equal to {{ error.min }}.
</span>
</div>
PS:如果您不關心將來的發行版中的中斷,但仍想使用Validators.min
,則只需更改以下行即可:
control.setValidators([Validators.required, customMin(min)]);
對此:
control.setValidators([Validators.required, Validators.min(min)]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.