最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show image before click to upload file in Angular 9? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

You 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();
}
发布评论

评论列表(0)

  1. 暂无评论