4

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

2
  • Is this.sharedDataService.inventoryRows an async operation? Can you provide that code as well? Commented Mar 1, 2018 at 0:11
  • What is the row that you are passing as an argument from the html? Commented Mar 1, 2018 at 2:31

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

you are returning from the foreach loop and not returning a value from the getMedia function, use for loop its faster and clear

 getMedia(row) {
       const data = this.sharedDataService.inventoryRows;
       for(let i = 0; i < data.length; i++;) {
         if(row.vin === data[i].vin){
            return data[i].media[0].href;
         }
       }
       return '';
 } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.