自定义验证在Angular中不起作用



我在Angular中有一个带有自定义验证的表单构建器,但在我在自定义验证中读取它后,我无法获得文件的类型。

这是stackblitz:

https://stackblitz.com/edit/angular-ivy-atwqqc?file=src%2Fapp%2Fapp.component.ts

TS文件
function checkFileType(
control: AbstractControl
): { [key: string]: any } | null {
const files: File = control.value;
const errors: string[] = [];
if (files) {
console.log(files);
if (files.type === "txt") {
errors.push(`${files[0].name} has an invalid type of unknownn`);
}
console.log(files.type); //This is always null. How can I get file type
return errors.length >= 1 ? { invalid_type: errors } : null;
}
return null;
}

onSelection($event) {
const fileReader = new FileReader();
const file = $event.target.files[0];
fileReader.readAsDataURL(file);
fileReader.onload = () => {
this.reactiveForm.patchValue({
file: fileReader.result
});
};  
}

问题来自readAsDataURL()。它将其编码为64进制字符串,这意味着它没有属性type可以查看。实际上它没有任何类型可以看因为它是string而不是File。如果您删除它,并将file变量设置为您的表单,您将获得所需的属性

function checkFileType(
control: AbstractControl
): { [key: string]: any } | null {
const file: File = control.value;
const errors: string[] = [];
if (file) {
console.log(file);
if (file.type === "txt") {
errors.push(`${file.name} has an invalid type of unknownn`);
}
console.log(file.type); //This is always null. How can I get file type
return errors.length >= 1 ? { invalid_type: errors } : null;
}
return null;
}

onSelection($event) {
const fileReader = new FileReader();
const file = $event.target.files[0];
fileReader.onload = () => {
this.reactiveForm.patchValue({
file: file
});
};  
}

最新更新