简体   繁体   English

Angular2:验证 <input type=“file”/> 更改要上载的文件时不会触发

[英]Angular2: validation for <input type=“file”/> won't trigger when changing the file to upload

Angular 2 seems to have troubles with running validation when a file input changes. 当文件输入发生变化时,Angular 2似乎在运行验证时遇到麻烦。

I made a plunk to illustrate this problem: 我做了一个插图来说明这个问题:

I make a formGroup like 我创建了一个formGroup

this.frm = new FormGroup({
    file: new FormControl("", this.validateFile)
});

And in the validateFile function I throw an alert and log to the console: 在validateFile函数中,我抛出一个警报并记录到控制台:

public validateFile(formControl: FormControl): {[key: string]: any; } {
   alert('Validation ran');
   console.log('Validation ran');
}

Plunkr to illustrate the issue: https://plnkr.co/edit/Pgcg4IkejgaH5YgbY3Ar?p=preview Plunkr来说明问题: https ://plnkr.co/edit/Pgcg4IkejgaH5YgbY3Ar?p = preview

The validation will run when initializing the page but won't run each time you change the file to be uploaded. 验证将在初始化页面时运行,但每次更改要上载的文件时都不会运行。

Is there any solution to this problem? 有没有解决这个问题的方法?

I fixed it using kemsky answer and Sebastien's comment. 我用kemsky答案和塞巴斯蒂安的评论修正了它。 I made a ngValueAccessor which registers itself on every input with type file. 我创建了一个ngValueAccessor,它在每个带有类型文件的输入上注册自己。

Plunkr can be found here . Plunkr可以在这里找到。

Most relevant code + explanation beneath: 最相关的代码+解释如下:

This adds a ControlValueAccessor for file inputs which might be part of the angular framework itself someday( #7341 ). 这为文件输入添加了一个ControlValueAccessor,有一天它可能是角度框架本身的一部分( #7341 )。 A file input works different than other controls. 文件输入与其他控件的工作方式不同。 This piece of code makes sure the selected files are read as the value: 这段代码确保将所选文件作为值读取:

import {Directive} from "@angular/core";
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from "@angular/forms";

@Directive({
    selector: "input[type=file]",
    host : {
        "(change)" : "onChange($event.target.files)",
        "(blur)": "onTouched()"
    },
    providers: [
        { provide: NG_VALUE_ACCESSOR, useExisting: FileValueAccessor, multi: true }
    ]
})
export class FileValueAccessor implements ControlValueAccessor {
    value: any;
    onChange = (_) => {};
    onTouched = () => {};

    writeValue(value) {}
    registerOnChange(fn: any) { this.onChange = fn; }
    registerOnTouched(fn: any) { this.onTouched = fn; }
}

And for the 'required' validation I made a validator which I use by adding the static validate method to the file FormControl for ReactiveForms. 对于'required'验证,我创建了一个验证器,我通过将静态验证方法添加到文件FormControl for ReactiveForms来使用。 (or as a directive for template driven forms). (或作为模板驱动形式的指令)。

import {Directive} from "@angular/core";
import {NG_VALIDATORS, Validator, FormControl} from "@angular/forms";

@Directive({
    selector: "[requiredFile]",
    providers: [
        { provide: NG_VALIDATORS, useExisting: FileValidator, multi: true },
    ]
})
export class FileValidator implements Validator {
    static validate(c: FormControl): {[key: string]: any} {
        return c.value == null || c.value.length == 0 ? { "required" : true} : null;
    }

    validate(c: FormControl): {[key: string]: any} {
        return FileValidator.validate(c);
    }
}

Building my form looks like this: 构建我的表单如下所示:

private buildForm() {
    this.frm = new FormGroup({
        file: new FormControl("",    [FileValidator.validate])
    });
}

And for the html: 而对于HTML:

<input type="file" formControlName="file"/>

Angular 4+ has changed there hostbindings. Angular 4+改变了主机绑定。

import { Directive, HostListener } from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";

@Directive({
    selector: "input[type=file]",
    providers: [
        {provide: NG_VALUE_ACCESSOR, useExisting: FileValueAccessorDirective, multi: true}
    ]
})
export class FileValueAccessorDirective implements ControlValueAccessor {
    @HostListener('change', ['$event.target.files']) onChange = (_) => {};
    @HostListener('blur') onTouched = () => {};

    writeValue(value) {}
    registerOnChange(fn: any) { this.onChange = fn; }
    registerOnTouched(fn: any) { this.onTouched = fn; }
}

目前不支持使用类型file输入,请参阅#7341

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM