The origin of the Angular img src becomes blurred when invoking a function

I want to dynamically change the image src by calling a function that returns the image path. However, when I attempt to do so using the code below, the image element displays 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);    // correct string gets logged
        return elem.media[0].href;
      }
    });
  }

This piece of code successfully logs the string stored in elem.media[0].href to the console, indicating that it is returning the correct path as a string.

HTML:

<img src="{{getMedia(row)}}" />
//The resulting DOM element shows up as <img src(unknown)/>

I have also tried the following suggested solutions from Stack Overflow, but unfortunately, they do not give me the desired DOM element either

<img [src]="getMedia(row)" />
//The resulting DOM element is displayed as <img src="null"/>

I am confident that this should work, but it seems like there is some underlying technical knowledge that I am missing about how it actually works

Answer №1

The function does not actually return any data, because the return statement in the .forEach loop only exits the loop and .forEach always returns undefined. To fix this issue, you can replace .forEach with something like .find, as demonstrated below:

function notWorking(){
  var items = [1,2,3,4,5];
  var value = items.forEach(function(num){
    if(num == 2)
       return num;
  });
  return value;
}

function working(){
  var items = [1,2,3,4,5];
  var value = items.find(function(num){
    if(num == 2)
       return num;
  });
  return value;
}


console.log("notWorking", notWorking());
console.log("working", working());

Answer №2

Try implementing a for loop instead of a foreach loop to improve efficiency and clarity in the getMedia function. Make sure you are returning a value from this function when exiting the loop.

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 '';
 } 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain a tuple of identical length from a function

I'm attempting to create a function that returns a tuple with the same length as the parameter tuple passed to it. Although I tried using generics, I am encountering an error when applying the spread operator on the result. My goal is best illustrate ...

An issue was encountered when attempting to log out the user from Firebase

My website is built using the Ionic and Angular Frameworks along with Firestore database. The signout feature works as expected, but unfortunately, an error occurs when a user tries to sign out of their account. The error message: FirebaseError: Missing o ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Broadening Cypress.config by incorporating custom attributes using Typescript

I'm attempting to customize my Cypress configuration by including a new property using the following method: Cypress.Commands.overwrite('getUser', (originalFn: any) => { const overwriteOptions = { accountPath: `accounts/${opti ...

In the Chrome task manager, an Angular 6 website is initially seen with a memory footprint of 1.3 GB, which then decreases to just 160 MB after a

While utilizing Angular 6, our website experiences a significant spike in memory footprint during loading, starting at 100MB and reaching 1.3GB before dropping back down to 160MB shortly after completion. https://i.sstatic.net/FhHB7.png https://i.sstatic. ...

Tips for effectively overriding a method in typescript

Why is this.fullName appearing empty in the show() method? class Person { protected name: string = ""; constructor(name: string) { this.makeSir(name); } makeSir(name: string) { this.name = "sir" + name; } } class M ...

Knexfile Doesn't Utilize TypeScript Paths

When attempting to run a migration, I encountered an issue with Knex. My Knexfile is in Typescript and uses path aliases from tsconfig.json. However, Knex is throwing an error stating Cannot find module '@foo-alias/bar-module'. What adjustments d ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Why is it that my side effect action is unable to identify the return action type property?

I've been working on setting up SideEffect for my authentication store, but every time I trigger the action (TrySignIn), I keep encountering this error: "AuthEffects.authSignin" dispatched an invalid action ERROR TypeError: Actions must hav ...

Fetching data from MongoDB, loading over 3000 entries and implementing pagination

I'm facing a challenge where I need to display more than 3000 results in an HTML table by fetching MachineID, Username, and Data from my MongoDB. However, I am encountering difficulties when trying to render this data using datatables. The MachineID ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Customize the text for the material icon

Can I customize an icon by using the following code: import FiberNewIcon from "@mui/icons-material/FiberNew"; Is there a way to add custom text to the icon? ...

Issue with excluding certain events from being identified in the polyfills.ts file in Angular 8

While developing an application in Angular 8 that utilizes jsPlumbToolkit to showcase and modify flowcharts, I encountered performance issues. Upon investigating, I discovered that the change detection from zone.js was triggering at every mouse move event. ...

Angular4 does not recognize this.form.get as a valid function

While working on my Angular 4 application, I encountered an issue with data binding to a form. Despite the code for binding appearing correct, there seems to be a problem that I can't quite pinpoint. Upon debugging the application, I noticed that the ...

Angular service designed for distributing a collection of data across nested levels

How can values be effectively shared across components within a specific hierarchy without having to pass them down individually, especially when some nodes require the values and others do not? It can become messy. I've been considering something li ...

Can you help me identify any issues with this code for uploading an image and quickly displaying it in Angular?

Located within the profile.component.html file <label for="profile">Profile Photo</label> <input type="file" [(ngModel)]='uploadedPhoto'/> <img [src]='uploadedPhoto'> Contained in the profile.component.ts file ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

The specified path "/src/app/app.module.ts" was not found while attempting to add ng in an Angular project that is using a custom path

I encountered an issue while attempting to integrate Angular Universal into my project. Here is my folder structure: src main app app.module.ts node_modules tsconfig.json My project uses Angular version 15.2.5 and the latest version of Angular Uni ...

Unable to display complete content of Ionic 3 webpage

Trying to print a specific part of an Ionic page which contains a long list of items. However, encountering an issue where the entire list doesn't fit on one page and requires scrolling down to view all items. Expecting the print dialog, triggered by ...

Is it possible to utilize an Angular2 service with the DOM addEventListener?

Issue: I am encountering an problem where the service appears to be empty when trying to call it within an addEventListener. Html: <div id="_file0"> Service: @Injectable() export class FilesService { constructor(private http : Http) { } } Co ...