角度2 |如何在FormControl中处理输入类型文件? [英] Angular 2 | How to handle input type file in FormControl?
本文介绍了角度2 |如何在FormControl中处理输入类型文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
美好的一天,
我如何处理formControl中的输入类型文件?即时通讯使用反应形式,但是当我得到形式的值时,它在我的<input type="file">
??
How can i handle input type file in formControl? im using reactive form but when i get the value of my form it returns null value on my <input type="file">
??
推荐答案
您需要编写自己的FileInputValueAccessor
.这是矮人和代码:
You need to write your own FileInputValueAccessor
. Here is the plunker and the code:
@Directive({
selector: 'input[type=file]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: FileValueAccessorDirective,
multi: true
}
]
})
export class FileValueAccessorDirective implements ControlValueAccessor {
onChange;
@HostListener('change', ['$event.target.value']) _handleInput(event) {
this.onChange(event);
}
constructor(private element: ElementRef, private render: Renderer2) { }
writeValue(value: any) {
const normalizedValue = value == null ? '' : value;
this.render.setProperty(this.element.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn) { this.onChange = fn; }
registerOnTouched(fn: any) { }
nOnDestroy() { }
}
然后您将能够获得如下更新:
And then you will be able to get updates like this:
@Component({
moduleId: module.id,
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<h3>File path is: {{path}}</h3>
<input type="file" [formControl]="ctrl">
`
})
export class AppComponent {
name = 'Angular';
path = '';
ctrl = new FormControl('');
ngOnInit() {
this.ctrl.valueChanges.subscribe((v) => {
this.path = v;
});
}
}
这篇关于角度2 |如何在FormControl中处理输入类型文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文