I am very new to typescript and web development in general so I am sorry if my code is terrible. Anyways, I am having an issue displaying a "preview image" for a profile picture upload. I am using ng2-file-upload to upload my image to the server and that part is working correctly. Before I click the upload button I want to display the selected image on the page right after it has been selected. Currently I am trying to display the image by retrieving the src property from the HTMLImageElement but the src property appears to be empty.
import { Component, OnInit } from '@angular/core';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
const URL = 'http://localhost:4200/api/upload';
@Component({
selector: 'app-view-profile',
templateUrl: './view-profile.component.html',
styleUrls: ['./view-profile.component.css']
})
export class ViewProfileComponent implements OnInit {
constructor() { }
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'newProfilePicture'});
title: string;
previewImage: any;
tempImage: any;
source: string;
imagePreview(input)
{
document.getElementById("previewImage").style.display="block";
console.log("Image is selected")
this.previewImage = document.getElementById("previewImage");
console.log(this.previewImage);
this.source = (<HTMLImageElement>document.getElementById('previewImage')).src
console.log("Image Source: " + this.source + " Should be inbetween here");
//var reader = new FileReader();
//console.log(this.previewImage);
}
ngOnInit() {
this.title = 'View or Update Your Profile';
this.uploader.onAfterAddingFile = (file)=> {file.withCredentials = false;};
this.uploader.onCompleteItem = (item:any, response:any, status:any, headers:any) => {
console.log("ImageUpload:uploaded:", item, status, response);
//this.imagePreview();
};
}
}
And here is my HTML
<div class="container">
<h1>{{title}}</h1>
<div>
<input type="file" id="previewImage" (change)="imagePreview(this);" name="newProfilePicture" ng2FileSelect [uploader] ="uploader" />
<button type="button" class="btn btn-success btn-s" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length">
Upload Your File
</button>
</div>
</div>