I've set up the following structure:
export class HomePageComponent implements OnInit {
constructor(private httpClient: HttpClient) {
}
nummer: FormControl = new FormControl("", this.nummerValidator());
firstname: FormControl = new FormControl("", [Validators.minLength(3)]);
lastname: FormControl = new FormControl("", [Validators.minLength(3)]);
formGroup: FormGroup = new FormGroup({
firstname: this.firstname,
lastname: this.lastname,
}, this.formGroupValidator());
ngOnInit() {
}
nummerValidator() {
return (control: FormControl): { [key: string]: any } | null => {
if (this.checkEmpty(control.value)) {
this.enableOnNumber();
return null;
}
this.disableOnNumber();
if (isNaN(control.value)) {
return {'forbiddenName': {value: control.value}};
}
return null;
}
}
enableOnNumber() {
this.firstname.enable();
this.lastname.enable();
}
disableOnCardNumber() {
this.firstname.disable();
this.lastname.disable();
}
formGroupValidator() {
return (control: FormGroup): { [key: string]: any } | null => {
//someStuffHere
return errorFound ? {'formGroupError': true} : null;
}
}
Upon loading the page with this setup, an error occurs stating that this.firstname
and this.lastname
are null within the enableOnNumber
function. This issue does not exist with the disableOnNumber
function.
Strangely, when I initialize the nummer FormControl without the validator and add the validator in the ngOnInit
function, everything functions correctly. Why does this approach work? Can anyone shed some light on this?
Here is the revised approach:
nummer: FormControl = new FormControl();
ngOnInit() {
this.nummer.validator = this.NummerValidator();
}