In my form array (experiencesArray), I have nested nested nested form controls (companyname), as shown below.
this.personalFormGroup = this._formBuilder.group({
professionalInfo: this._formBuilder.group({
totalexpyears: ['', Validators.required],
}),
experiencesArray: this._formBuilder.array([this.experiences()])
})
The form group for experiences is outlined below:
experiences(): FormGroup {
return this._formBuilder.group({
companyName: [''],
})
}
I need to set validators based on the value of totalexpyears in the professional form group. If the value is greater than 0, the companyName field should be required; otherwise, it should not. I'm using the following method to set validators:
workExperience(value){
const expValidation = <FormControl>this.personalFormGroup.get('professionalInfo').get('experiencesArray.expDesignation');
this.personalFormGroup.get('professionalInfo').get('totalexpyears').valueChanges.subscribe((value)=>{
console.log("Inside value", value);
if(value > 0){
this.totalExpYearsValue = true;
console.log("Inside value greater than 0", this.totalExpYearsValue);
expValidation.setValidators([Validators.required]);
}
if(value == 0){
this.totalExpYearsValue = false;
console.log("Inside value lesser than 0", this.totalExpYearsValue);
expValidation.clearValidators();
}
expValidation.updateValueAndValidity();
});
}
Additionally, the totalexpyears field is a material dropdown and the template code is shown below:
<form [formGroup]="personalFormGroup">
<div formGroupName="professionalInfo">
<mat-form-field>
<mat-select (selectionChange)="workExperience($event.value)" formControlName="totalexpyears" placeholder="Total Exp yrs *" class="select">
<mat-option *ngFor="let exp of experience" [value]="exp">
{{exp}}
</mat-option>
</mat-select>
<mat-error *ngIf="(personalFormGroup.get('professionalInfo').get('totalexpyears').errors)">
<mat-error *ngIf="(personalFormGroup.get('professionalInfo').get('totalexpyears').errors.required && personalFormGroup.get('professionalInfo').get('totalexpyears').touched)">
Experience is required
</mat-error>
</mat-error>
</mat-form-field>
<div class="design" *ngIf="this.totalExpYearsValue">
<!-- Experience section -->
</div>
</div>
</form>
An error I encountered is displayed below:
ERROR TypeError: Cannot read property 'setValidators' of null
at steppar.component.ts:590
...
The focus is on setting validators based on experience value. Please disregard other aspects such as syntax errors or HTML structure.