【发布时间】:2019-04-28 04:48:32
【问题描述】:
我正在使用 Angular 5 反应形式。 因为我有一个浏览字段,在该浏览按钮的更改事件中我正在调用一个函数,在该文件验证中进行检查。 如果文件无效,我将手动为该字段设置错误。
现在我期待的是何时设置文件输入错误。错误消息应显示在 DOM 中。它适用于 Chrome、Firefox 和 Android 设备。但它在 IE 和 IOS 中不起作用。
HTML 代码
<div class="form-group" [ngClass]="{'has-error': hasError('profileimage')}">
<label class="control-label"> Upload Profile Image...</label>
<input id="profileimage"
(change)="fileUpload($event.target.files,'profileimage')"
type="file"
formControlName="profileimage">
<span class="is-error" *ngIf="checkValidImageFormat('profileimage')">
Only file with extensions are allowed: .png, .jpeg, .jpg .</span>
<span class="is-error" *ngIf="checkValidImageSize('profileimage')">File must be less than 1 MB .
</span>
</div>
Component.ts
fileUpload(files: FileList, field) {
this.profileimage = files[0];
let extension = this.profileimage.name.match(/(?:\.([^.]+))?$/)[1];
//checking the extension of the file
if (extension.toLowerCase() === 'jpg' ||
extension.toLowerCase() === 'jpeg' ||
extension.toLowerCase() === 'png') {
var sizeInMB = (this.profileimage.size / (1024 * 1024)).toFixed(2);
//checking the file size should be less than 1 mb
if (!parseFloat(sizeInMB) < 1) {
this.contactForm.controls[field].setErrors({ 'invalid_size': true });
}
}
checkValidImageSize(fieldName) {
return this.contactForm.controls[fieldName].errors.invalid_size;
}
我已经尝试了所有角度的变化检测策略(NgZone、ChangeDetectorRef 等),但都没有奏效。 任何帮助将不胜感激。
【问题讨论】:
-
看看here
-
IE中是否有控制台错误?
标签: javascript angular angular-reactive-forms