5

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?

1
  • Clicks on an image? Do you mean the image loaded by the user or another one? Commented Jun 21, 2020 at 16:33

2 Answers 2

8

You can you do it like this:

component.ts

import { Component, VERSION } from "@angular/core";
import { SafeUrl, DomSanitizer } from "@angular/platform-browser";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
  constructor(private sanitizer: DomSanitizer) {}

  image: string | SafeUrl =
    "https://images.unsplash.com/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])
    );
  }
}

component.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.com/edit/stackoverflow-62501330

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.