我正在尝试学习角度5.在创建表单中有一个文件字段
<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>
我创建了一个customValidator类并在模块中注册。为了在更改时启动验证器,我添加了@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);
}
}
但是,代码没有给我任何验证错误。请找出所需的更正。