javascript - 在单击以在Angular 9中上传文件之前显示图像?
问题描述
我在当前的 Angular 项目中有这样的代码来上传文件:
<input #file type="file" accept='image/*' (change)="Loadpreview(file.files) " />
如何更改此设置,以便在用户单击图像时上传?
解决方案
你可以这样做:
组件.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])
);
}
}
组件.html
<p>
Image uploader :)
</p>
<img [src]="image" (click)="selectImage.click()">
<input type="file" (change)="updateImage($event)" style="display: none" #selectImage>
您实际上是通过引用输入元素的 id 来调用点击处理程序
请在此处找到您的问题的工作示例:https ://stackblitz.com/edit/stackoverflow-62501330
推荐阅读
- javascript - 在玩笑测试中忽略某些导入函数的最佳方法
- python - Big Sur 上的 2019 Macbook Pro + 最新版 Spyder 上的 Pandas 导入错误
- python - 如何删除Python列表最后一个元素中的字符?
- amazon-web-services - Terraform 中 for_each 循环的动态输出
- python - 更改列表列表中的值
- asp.net-core - 无法将 _UserLayout.cshtml 连接到访客区的仪表板
- php - 按父类别划分子类别 - WordPress
- c# - 无法推断 C# 类型参数
- c# - 使用右键单击而不是左键单击作为统一按钮
- elasticsearch - 如何从祖父母那里获得elasticsearch 7.10中的所有孙子