When creating a custom validation function in Angular, I encountered an issue where using a variable within the validation would result in an error: "ERROR TypeError: Cannot read properties of undefined (reading 'file')". This occurred when changing the value in the form. The custom extension file for validation required me to declare and assign a value to the variable inside it. I am trying to understand why this error is happening. Could it be that the custom validate function is not observing changes and executing before other functions? Why does the variable value not exist and end up being assigned to undefined? Also, how can I use the file size in the validate file size function? Below is the component code:
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { PagedResult } from 'src/app/core/models/pagedResult.model';
import { AlertService } from 'src/app/core/services/alert.service';
import { FakeDataService } from 'src/app/core/services/fake-data.service';
import { Employee } from '../../models/employee.model';
import { PenaltyReason } from '../../models/penalty-reason.model';
import { PenaltyType } from '../../models/penalty-type.model';
import { Penalty } from '../../models/penalty.model';
@Component({
selector: 'app-penalties',
templateUrl: './penalties.component.html',
styleUrls: ['./penalties.component.css']
})
export class PenaltiesComponent implements OnInit {
penalties: PagedResult<Penalty>;
page = 1;
formTitle = "اضافة عقوبة";
penaltyTypes: PenaltyType[];
penaltyReasons: PenaltyReason[];
employees: Employee[];
selectedPenaltyIndex: number;
penaltyForm: FormGroup;
file: FormControl;
constructor(private fakeData: FakeDataService, private alert: AlertService) { }
loadData() {
this.fakeData.getDataFor('Penalties', this.page).then(result => {
this.penalties = result as PagedResult<Penalty>;
});
}
// Other component methods...
}