I am trying to learn angular 5. In a create form there is a file field
<input type="file" class="form-control-file" formControlName = "fileInput" fileInput >
<div *ngIf="angForm.controls.fileInput.sizeinvalid && (angForm.controls.fileInput.dirty || angForm.controls.fileInput.touched)" class="alert alert-danger">
<div *ngIf="angForm.controls.fileInput.errors.invalid">Maximum allowed image Size is 5 MB</div>
</div>
and I have create a customValidator class and registered in module. To initiate the validator on change I have added @HostListener
@Directive({
selector: "[fileInput]",
providers: [
{ provide: NG_VALIDATORS, useExisting: FileValidator, multi: true },
]
})
export class FileValidator implements Validator {
constructor(private el: ElementRef) { }
@HostListener('change', ['$event.target']) onChange(target) {
this.validate(this.el.nativeElement);
}
static validate(c: FormControl): {[key: string]: any} {
if (c.size > 0) {
console.log("Maximum size")
return { "sizeinvalid" : true};
} else {
console.log('No size');
return null;
}
}
validate(c: FormControl): {[key: string]: any} {
return FileValidator.validate(c);
}
}
But, the code is not getting me any validation errors. Please figure out corrections needed.