I am starting with simple Typescript(.ts)+HTML(.js) code for practice. In HTML page I have below tag to display certain image :
<img id="myimage" src='images/samsung_edge_silver.jpg' height="250px">
<div><b><span id="Name"></b></div>
I am starting with simple Typescript(.ts)+HTML(.js) code for practice. In HTML page I have below tag to display certain image :
<img id="myimage" src='images/samsung_edge_silver.jpg' height="250px">
<div><b><span id="Name"></b></div>
Now I have ts file to alter fields in this code. I can change the value of span field Name using :
document.getElementById("pName").innerHTML = productName;
But is there any way I can alter the value of source URL for myimage.
I read a few answers, people are giving an answer for angular mostly. But this is pure typescript+html. How do we assign a new value to image source?
Share Improve this question edited Jul 19, 2019 at 8:25 Nazim Kerimbekov 4,7839 gold badges36 silver badges58 bronze badges asked Jul 19, 2019 at 8:24 Vishnu DahatondeVishnu Dahatonde 1893 silver badges13 bronze badges3 Answers
Reset to default 4You have to do this:
(document.getElementById('test') as HTMLImageElement).src = 'http://www.image.';
The reason for this is that document.getElementById('id')
will return an HTMlElement and not all HTMLElement have src
property.
You can set it like this.
document.getElementById('myimage').src = 'http://yourImagePathHere';
Checkout the fiddle here
If you are using angular, you can do something like this:
HTML:
<img [src]="mySource">
Typescript:
mySource = "/maybeAssets/default.png";
changeSourceImage() {
this.mySource = "/maybeAssets/funnyCats.png"
}