我希望能够从<input type="file" id="fileLoader">
中的上传图像更新图像SRC属性,我已经使用香草JS了。我该如何在Angular组件中做同样的事情
我的代码在下面
使用JavaScript
window.addEventListener('load', function() {
document.querySelector('#fileLoader').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img');
img.src = URL.createObjectURL(this.files[0]);
}
});
});
<img src="https://via.placeholder.com/150" alt="">
我该如何在角度分量中复制它?
Mikegross的答案是正确的,但不完整。 Angular的消毒器机制将对该URL发牢骚。您需要通过它。像这样:
import { Component } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular";
myModel: string | any = "";
constructor(private sanitizer: DomSanitizer) {}
public uploadImage(event: any) {
const url = URL.createObjectURL(event.target.files[0]);
this.myModel = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
正在工作的stackblitz样本
我认为您可以简化很多事情
1)使用两种方式进行数据绑定和ngModel将您的url值绑定到您的输入:
<!-- your input element -->
<input type="file" (change)="uploadImage($event)"/>
// extract the url of the data and let it appear
public uploadImage(event: any) {
this.myModel = URL.createObjectURL(event.target.files[0])
}
2)您的图像
<img [src]="myModel">
这应该工作!