Naprawiłem go za odpowiedź kemsky i Sebastien za komentarz. Zrobiłem ngValueAccessor, który rejestruje się na każdym wejściu z plikiem typu.
Plunkr można znaleźć here.
Najbardziej odpowiedni kod + wyjaśnienie poniżej:
To dodaje ControlValueAccessor wejść plików, które mogą być częścią ram kątowej sama kiedyś (#7341). Dane wejściowe pliku różnią się od innych elementów sterujących. Ten fragment kodu pilnuje wybrane pliki są odczytywane jako wartość:
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; }
}
A dla „wymagana” walidacji Zrobiłem walidator który używam dodając statycznej metody sprawdzania poprawności do FormControl plików dla ReactiveForms. (lub jako dyrektywa dla formularzy opartych na szablonach).
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);
}
}
budowy mój formularz wygląda następująco:
private buildForm() {
this.frm = new FormGroup({
file: new FormControl("", [FileValidator.validate])
});
}
A dla HTML:
<input type="file" formControlName="file"/>
Dziękuję bardzo za dostarczenie tej próbki kodu. To właśnie uratowało mój dzień. – Brandon
Przydatne. Thansk! – user3757628
To działało. Dziękuję Ci! – Sagar