Set Image Src in TypeScript
Asked Answered
M

2

9

I'm using ionic 2 and want to load a picture during runtime. In the past projects I always did it like this:

bikeImage.src = "data:image/jpeg;base64," + bikeResult.image;

But it doesn't work in TypeScript.

My HTML looks like this.

<img id='bikeImage'/>

It says, that src is a unresolved variable.

I thought that every JavaScript code works in TypeScript as well. Am I wrong?

Does anybody have an idea how to fix this?

Thanks in advance.

Melissiamelita answered 1/11, 2016 at 11:56 Comment(0)
R
31

You haven't posted how you get element into bikeImage, but it should be:

bikeImage = document.getElementById("bikeImage") as HTMLImageElement;

If you don't type assert it to HTMLImageElement then it will be just an HTMLElement which does not have the src property.

Ritaritardando answered 1/11, 2016 at 12:0 Comment(1)
Thanks alot. I´ve never heard of that before.Melissiamelita
P
0

I maybe late but I found the best and simple way. Angular 15 using latest typescript version.

Create a function inside your component. See below:

onSelectImage(image: any){
document.images[document.images.length - 1].src = image.convertedProductImage;}

Call it from your html such as (click)="onSelectImage(image)". Open dev tools and double check what index of your target element in the document images. This should swap images.

The parameter passed is the image base64:

"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkJCggKCAsLCQsKCwsLDhAMCgsNExcVEBQPFhISDhYSDxQPDxQSFBgTFhQZIBoeGRgrIRwkExwdMiIzKjclIjABBgsKCw0OCwwMDg4MDRAOHRQNDCIUFRcOHggXDBAWEBEXCxATFAsRGREeCRkMCCIYHRQPHRANDA8WEAsUFSMWGP/CABEIAwADwgMBIgACEQEDEQH/xAA1AAEAAgMBAQEAAAAAAAAAAAAAAQMCBAUGBwgBAQACAwEBAAAAAAAAAAAAAAABAgMEBQYH/9oADAMBAAIQAxAAAAD7iAAAAAAAAAAAAAAAAAAAAAAcU7TxnAPofI8LSn1/Z+b9ZH0Tc8P3k9oIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEEuRxT2On840U+54HAk2KMQiddG3h8w+nDLUlPT6XnOkfWwgAAAAAAAAAAAAAAAAAAAAAAAAAA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fT6X6b/J/37Jpe4AAAAAAAAAAAAAAABj8o+kfNkgAQCAQCvTnYmLRE6/jPaeXR4Oym87/ANR+RfXe96JEur1oTAAzwyhsfDfuHg9HnbH2P8t/qT5/xQ5dgAFPnPkexf13kfR7/M9PpbqPP+gCl5mJJzwztTOcct/DIz1xjKLMPO+jxyYeD9f+Yed6Xmfvzi9qnJCoAAEwlCAAfNvIfTfmu39C1a7MNvY0PS+e3a7vXrzw0/RVc/o6mzx+N9Z+Te59H8O++gAAAAAAAAAAAAAAA4HhfW+STCYETABAITgc3p8zpzECJp4Pf5R8q2dbZRd9p+I/Z+x29gdruhJEwJgW62xdip+c/wBIfDvaeL8x9mHlZETE/L+Znt7PD9jt6vE9hRjnhweoiVZgEzEk5Y5TXPLHLoYcolsUxjLGzHHPCJw09ynHPlPt/wAq0ev5X7sxyjigAAAlEoQDT+Nfcfk2b1fmqrqd/v1au3p5MHqI09zQ9lVRfrWpxe1yXp/gH6xYZzQAAAAAAAAAAAAAADwfC6POSiYBABAGts8+U7tF8IBhy+vzT5PYIn638k+ndLq+hTHf9GEkTEgTN+vbSvh/EfYfg3E4X66ee9D881Hyv2PkadKv0V9ODtaWpvael0tfCyvkbsClgExJMxKLMsM9/DkNjHEZRkjDHPBNdN9OK2tw+5z7Y/Y+/wDgX3rr+KziYpqAAAABEx4v2uhO/wDFNbe0ul7+qi+vLqU+j8n6TF2c9fY18Ha5dOzq+j+Gfp/r+K9rl5g......"

Such as that example

Pridemore answered 27/5, 2023 at 5:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.