我正在尝试为输入图像验证编写自定义指令。我想验证选择的图像的宽度是否高于X值(示例中为300)。
<input id="imageFile" minWidth="300" minHeight="300" name="image" type="file" ngModel #image="ngModel">
<div *ngIf="image.invalid">
<p *ngIf="image.errors.width" >width should be higher than 300px!</p>
</div>
import { Directive, HostListener, Input } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn } from '@angular/forms';
@Directive({
selector: '[minWidth]',
providers: [{provide: NG_VALIDATORS, useExisting: ImageMinWidthDirective, multi: true}]
})
export class ImageMinWidthDirective implements Validator {
@Input() minWidth: number;
private width = 0;
file: any;
image: any;
@HostListener('change', ['$event']) onChange($event) {
const files = $event.target.files || $event.srcElement.files;
this.file = files[0];
}
validate(control: AbstractControl): {[key: string]: any} {
return this.minWidth ? this.minWidthValidator()(control)
: null;
}
minWidthValidator(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
this.image = new Image();
this.image.onload = event => {
this.width = event.path[0].width;
alert(this.image.width);
};
this.image.src = window.URL.createObjectURL(this.file);
return this.width < this.minWidth ? {'width': {value: 'hello'}} : null;
};
}
}