'having problem using form.controls.errors.(myError) (error is from AbstractControl) in ngClass in angular
I have created an validation (in ReactiveForm) using abstractControl and wanted to use it in ngClass.
here is my code:
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 class="form-input" formControlName="current_password">
</div>
<div>
<label>Password : </label>
<input class="input-form" formControlName="new_password" [ngClass]="{ 'red-border': inputForm.errors.equation }">
</div>
<div>
<label>Password Confirmation : </label>
<input class="input-form" formControlName="re_new_password" [ngClass]="{ 'red-border': inputForm.errors.equation }">
</div>
</form>
when this form get valid equation error will get null and that's where I have problem with ngClass because no error called 'equation'
how should i solve this ?
Solution 1:[1]
You need ?. optional chaining to escape the possibly null error.
As FormGroup's error is with ValidationErrors or null type.
errors: ValidationErrors | null
<input
class="input-form"
formControlName="new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation }"
/>
<input
class="input-form"
formControlName="re_new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation }"
/>
And also correct the statement as new_pass and re_new_pass doesn't exist as the FormControl (typo error) as below:
if (form.value.new_password === form.value.re_new_password)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong Shun |
