Ojay
Ojay

Reputation: 703

Angular eventListener from Component

I want to be able to update an image SRC attribute from an uploaded image in an <input type="file" id="fileLoader">, i have already this using vanilla JS. How do i do do the same in Angular component

my codes are below

Using 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="">

how do i replicate this in angular component?

Upvotes: 0

Views: 482

Answers (2)

Eldar
Eldar

Reputation: 10790

Mikegross answer is correct but not complete. Angular's sanitizer mechanism will whine about that url. You need to by pass it. Like this :

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);
  }
}

Working stackblitz sample

Upvotes: 1

mike
mike

Reputation: 1863

You can simplify this quite a lot in my opinion

1) use two way data binding and ngModel to bind your url value to your input:

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

3) in your component

// extract the url of the data and let it appear
public uploadImage(event: any) {
  this.myModel = URL.createObjectURL(event.target.files[0])
}

2) your image

<img [src]="myModel">

this should work!

Upvotes: 1

Related Questions