在 Angular 9 中单击上传文件之前显示图像?

use*_*940 5 html javascript angular

我当前的角度项目中有这样的代码来上传文件:

<input #file type="file" accept='image/*'  (change)="Loadpreview(file.files) " />
Run Code Online (Sandbox Code Playgroud)

如何更改此设置,以便当用户单击图像时它可以上传?

leo*_*afa 8

你可以这样做:

组件.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])
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

组件.html

<p>
    Image uploader :)
</p>
<img [src]="image"  (click)="selectImage.click()">
<input type="file" (change)="updateImage($event)" style="display: none" #selectImage>
Run Code Online (Sandbox Code Playgroud)

您本质上是通过引用输入元素的 id 来调用点击处理程序

请在此处找到解决您问题的工作示例:https ://stackblitz.com/edit/stackoverflow-62501330