user13520940
user13520940

Reputation: 143

Show image before click to upload file in Angular 9?

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?

Upvotes: 5

Views: 5015

Answers (2)

leonlafa
leonlafa

Reputation: 318

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

Upvotes: 8

בלימי בוימל
בלימי בוימל

Reputation: 41

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

Upvotes: 0

Related Questions