This code in my form-validators.ts:
console.log('password:', password?.value); console.log('confirmPwd:', confirmPwd?.value); always fetched me undefined, causing the custom validation (matchPwdValidator()) to constantly return false. If I fetched confirmPwd in the switch, it will print out the correct details. Below is a summarized version of my codes.
form-validators.ts
import { AbstractControl, ValidatorFn, Validators } from "@angular/forms"; export class FormValidators { ... static matchPwdValidator(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { const password = control.get("password"); const confirmPwd = control.get("confirmPwd"); console.log('password:', password?.value); console.log('confirmPwd:', confirmPwd?.value); if (!password || !confirmPwd || password.value !== confirmPwd.value) { return { PwdNotMatched: true }; } return null; }; } } form.component.ts
import { Component } from "@angular/core"; import { FormBuilder, FormGroup } from "@angular/forms"; import { FormValidators } from "../utilities/form-validators"; @Component({ selector: "app-form", templateUrl: "./form.component.html", styleUrls: ["./form.component.scss"], }) export class FormComponent { cpwdError: boolean = false; sampleForm: FormGroup; constructor( private formBuilder: FormBuilder, ) { this.sampleForm= this.formBuilder.group( { ... password: ["", FormValidators.passwordValidator()], confirmPwd: ["", FormValidators.matchPwdValidator()], }, ); ... this.sampleForm.get('confirmPwd')?.statusChanges .subscribe(() => { this.updateErrorFlags('confirmPwd'); }); } private updateErrorFlags(controlName: string): void { const control = this.sampleForm.get(controlName); if (control) { switch (controlName) { ... case 'confirmPwd': this.cpwdError = control.hasError('PwdNotMatched') && control.dirty; break; } } } }
control.parent?.get()inplace ofcontrol.get("");control.parent?.get()fixed the problem. May I know whycontrol.get("")doesn't work?