Pass image from FileReader to form input in Angular 6

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 21:45:24

Okay, the line giving you he error was this.imageUpload.controls.imageInput.setValue(files[0]);

The reason is, the browser will prevent you from programmatically setting the file that way due to security problems.

Instead, you can use the e.dataTransfer.files directly:

let input = this.imageUpload.controls.imageInput as any;
input.files = files;  

Here is a fork of your stackblitz

What you are trying to do can't be achieve this way (cause of what every people said, security reason etc...).

To acheive what you want to do, an Angular Solution is to create a custom component working with [(ngModel)] formControlName by implementing the ControlValueAccessor.

By doing this you will be able to put what ever you want as value into the FormControl.

Implementing ControlValueAccessor is part of many tutorial : https://blog.angularindepth.com/never-again-be-confused-when-implementing-controlvalueaccessor-in-angular-forms-93b9eee9ee83

Here you can find some code of my own, an image-chooser working in a Form :

https://github.com/xrobert35/asi-ngtools/blob/master/src/components/asi-image-chooser/asi-image-chooser.component.ts

example : https://ng-tools.asi.fr/views/showroom/asi-ngtools/components/asi-image-chooser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!