I have code like this in my current angular project to upload a file:
<input #file type="file" accept='image/*' (change)="Loadpreview(file.files) " />
How can I change this so it can upload when the user clicks on an image instead?
I have code like this in my current angular project to upload a file:
<input #file type="file" accept='image/*' (change)="Loadpreview(file.files) " />
How can I change this so it can upload when the user clicks on an image instead?
Share Improve this question edited Jun 25, 2020 at 2:30 leonlafa 3182 silver badges8 bronze badges asked Jun 21, 2020 at 16:22 user13520940user13520940 1432 silver badges8 bronze badges 1- Clicks on an image? Do you mean the image loaded by the user or another one? – Guerric P Commented Jun 21, 2020 at 16:33
2 Answers
Reset to default 8You can you do it like this:
ponent.ts
import { Component, VERSION } from "@angular/core";
import { SafeUrl, DomSanitizer } from "@angular/platform-browser";
@Component({
selector: "my-app",
templateUrl: "./app.ponent.html",
styleUrls: ["./app.ponent.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
constructor(private sanitizer: DomSanitizer) {}
image: string | SafeUrl =
"https://images.unsplash./photo-1521911528923-9c3838123490?ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80";
updateImage(ev) {
this.image = this.sanitizer.bypassSecurityTrustUrl(
window.URL.createObjectURL(ev.target.files[0])
);
}
}
ponent.html
<p>
Image uploader :)
</p>
<img [src]="image" (click)="selectImage.click()">
<input type="file" (change)="updateImage($event)" style="display: none" #selectImage>
You essentially call the click handler by referencing the id of the input element
Please find a working example to your problem here: https://stackblitz./edit/stackoverflow-62501330
in the HTML:
<img src="image" alt="" (click)="selectImage()">
in the ts:
selectImage()
{
let input = document.createElement('input');
input.type = 'file';
input.accept="image/*";
input.click();
}