【问题标题】:Angular eventListener from Component来自组件的角度事件监听器
【发布时间】:2020-03-27 04:18:27
【问题描述】:

我希望能够从<input type="file" id="fileLoader"> 中的上传图像更新图像 SRC 属性,我已经使用 vanilla 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="">

如何在角度组件中复制它?

【问题讨论】:

  • “我如何在角度组件中复制它?”不清楚你的问题是什么。如何为组件中的元素添加事件监听器?
  • 如果你在哪里做我的代码在角度组件中做的同样的事情?
  • 您也没有说明 Angular 的版本。
  • Angular cli:8.3.19

标签: javascript html angular dom


【解决方案1】:

在我看来你可以简化很多

1) 使用两种方式数据绑定和 ngModel 将您的 url 值绑定到您的输入:

<!-- your input element -->
<input type="file" (change)="uploadImage($event)"/>

3) 在你的组件中

// 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">

这应该可行!

【讨论】:

  • 不确定如何处理文件输入......它不是用户拥有的文本框。
  • 如果这是一个文件输入,只需将(更改)事件侦听器用于设置 url 的函数...
  • 这样你的意思是&lt;input type="file" id="fileLoader" (change)="upload(this)"/&gt;upload(input) { if (input.files &amp;&amp; input.files[0]) { const avatarImg: HTMLImageElement = document.querySelector('img'); avatarImg.src = URL.createObjectURL(input.files[0]); } }
  • 不,您可以使用事件直接访问您的文件
  • 仍然没有任何反应
【解决方案2】:

Mikegross 的答案是正确的,但并不完整。 Angular 的 sanitizer 机制会抱怨那个 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 示例

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 2019-12-31
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多