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 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>
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 ?
CodePudding user response:
You need ?.
optional chaining to escape the possibly null error.
As FormGroup's error is with ValidationErrors
or null
type.
errors: ValidationErrors | null
<input
formControlName="new_password"
[ngClass]="{ 'red-border': inputForm.errors?.equation }"
/>
<input
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)
CodePudding user response:
Change your .ts file like below
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}
}
])
and your template must be like this
<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>
Pay attention to question mark. it makes sure you won't see null and undefined.