I need to dynamically change the img src by calling a function that returns the image path, but when I use the code below, the image element shows as <img src(unknown)/>
component.ts:
getMedia(row) {
this.sharedDataService.inventoryRows.forEach(function(elem){
if(row.vin === elem.vin){
console.log(elem.media[0].href); //logs string correctly
return elem.media[0].href;
}
});
}
this code successfully logs the string stored in elem.media[0].href to the console, so I'm confident it is returning the correct path as a string.
HTML:
<img src="{{getMedia(row)}}" />
//DOM element comes back as <img src(unknown)/>
I've also tried the following, as suggested by other Stackoverflow answers, but I don't get the desired DOM element using this either
<img [src]="getMedia(row)" />
//DOM element comes back as <img src="null"/>
I'm certain that this should be possible, but I'm clearly missing some behind-the-scenes knowledge about its inner workings
You aren't actually returning any data from the function, as the return keyword in .forEach only breaks the loop, and also .forEach only ever returns undefined. The issue can be resolved by substituting .forEach for something like .find as shown below:
function broken(){
var list = [1,2,3,4,5];
var value = list.forEach(function(num){
if(num == 2)
return num;
});
return value;
}
function working(){
var list = [1,2,3,4,5];
var value = list.find(function(num){
if(num == 2)
return num;
});
return value;
}
console.log("broken", broken());
console.log("working", working());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With