I am facing an issue with attaching a custom validator to an Angular Form Control. The Form Controls are initialized in the ngOnInit method, and I want the validator to check if a field has input only when a boolean class member this.shouldCheck
is true.
The problem arises when trying to access this class member from the validator function as it cannot find the instance of this
. Despite TypeScript supposedly solving scoping issues with this
, I am unable to figure out how to check the boolean in the validator.
This is a snippet of my component.ts:
// The value of shouldCheck is tied to a checkbox on the form
private shouldCheck: boolean = false;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.employeeCreateForm = this.formBuilder.group({
firstName: [null, [
this.myRequiredValidator,
Validators.maxLength(30),
Validators.pattern('[^<|]+$')]],
lastName: [null, [
this.myRequiredValidator,
Validators.maxLength(40),
Validators.pattern('[^<|]+$')]]
}
And here is my custom validator:
myRequiredValidator(control: AbstractControl): ValidationErrors | null {
// Perform basic "required field" validation if shouldCheck is true
if (this.shouldCheck) {
return !!control.value ? null : {required: true};
}
// Do not apply validation error otherwise
return null;
}
Regardless of where I initialize shouldCheck
, the validator function struggles to resolve this
and therefore fails to instantiate the FormGroup.
I even attempted using a simple null check:
if (this && this.shouldCheck) {
// Validate fields
}
However, this workaround allows the FormGroup construction but still encounters difficulties resolving this
, even after initialization. While I understand ngOnInit runs after the constructor, I have exhausted all possibilities and would appreciate any help.
Thank you.