I have input file (without submit - typicall input file). I'd like to call some function when chose file.
Example: I click on "Choose file" -> choose file -> now system detects change and call some function which prints all these file information (for example image name).
I can't use ngModel on input file, right? How to do that?
Use the following in your template:
<div class="modal-body">
<input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
<img id="preview" src="" alt="Preview">
</div>
Then your Component fileChangeEvent()
as
public fileChangeEvent(fileInput: any){
if (fileInput.target.files && fileInput.target.files[0]) {
var reader = new FileReader();
reader.onload = function (e : any) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(fileInput.target.files[0]);
}
}
All Your File related info will console....
Here's my amendments to Double H's answer to not rely on jQuery and stop the webpack erroring out on e.target.result.
<img [src]="imageSrc" alt="" />
<input type="file" capture="camera" accept="image/*" (change)="displayPhoto($event)">
Typescript Code
displayPhoto(fileInput) {
if (fileInput.target.files && fileInput.target.files[0]) {
const reader = new FileReader();
reader.onload = ((e) => {
this.imageSrc = e.target['result'];
});
reader.readAsDataURL(fileInput.target.files[0]);
}
}
Double H's function didn't work for me till I added onclick="this.value = null" as found here: https://stackoverflow.com/a/42357862/634650
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With