我使用 abstractControl 創建了一個驗證(在 ReactiveForm 中),并希望在 ngClass 中使用它。
這是我的代碼:
inputForm = new FormGroup({
current_password: new FormControl('', [
Validators.required
]),
new_password: new FormControl('', [
Validators.required
]),
re_new_password: new FormControl('', [
Validators.required
])
}, [
(form: AbstractControl) => {
if (form.value.new_pass === form.value.re_new_pass) {
return null;
}
return { equation: true }
}
])
html:
<form [formGroup]="inputForm">
<div>
<label>Current Password : </label>
<input formControlName="current_password">
</div>
<div>
<label>Password : </label>
<input formControlName="new_password" [ngClass]="{ 'red-border': inputForm.errors.equation }">
</div>
<div>
<label>Password Confirmation : </label>
<input formControlName="re_new_password" [ngClass]="{ 'red-border': inputForm.errors.equation }">
</div>
</form>
當這個表單獲得有效的方程式錯誤將變為空,這就是我對 ngClass 有問題的地方,因為沒有錯誤稱為“方程式”
我應該如何解決這個問題?
uj5u.com熱心網友回復:
更改您的 .ts 檔案,如下所示
inputForm = new FormGroup({
current_password: new FormControl('', [
Validators.required
]),
new_password: new FormControl('', [
Validators.required
]),
re_new_password: new FormControl('', [
Validators.required
])
}, [
(form: FormGroup) => {
if (form.controls.new_password.value === form.controls.re_new_password.value) {
return null;
}
return {equation: true}
}
])
你的模板必須是這樣的
<form [formGroup]="inputForm">
<div>
<label>Current Password : </label>
<input formControlName="current_password">
</div>
<div>
<label>Password : </label>
<input formControlName="new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation}">
</div>
<div>
<label>Password Confirmation : </label>
<input formControlName="re_new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation}">
</div>
</form>
注意問號。它確保您不會看到 null 和 undefined。
uj5u.com熱心網友回復:
您需要?.可選鏈接來逃避可能為空的錯誤。
由于FormGroup的錯誤在于ValidationErrors或null型別。
errors: ValidationErrors | null
<input
formControlName="new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation }"
/>
<input
formControlName="re_new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation }"
/>
并將陳述句更正為(錯字錯誤)不存在,new_pass如下所示:re_new_passFormControl
if (form.value.new_password === form.value.re_new_password)
StackBlitz 上的示例演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/426623.html
