Utilize Angular to dynamically bind the image source from a TypeScript function

Is there a way to dynamically bind the src attribute of an img tag in Angular by calling a function from Typescript? Here's the HTML code snippet:

<button (click)="createBoard()"> Create Board</button>
<table>
 <tr *ngFor="let i of board; let a = index">
  <td *ngFor="let j of i; let b = index">
    <div class="bDefault">
      <img src="getImage(a,b)"  
      (click)="changeImg(a,b, $event)">
    </div>
  </td>
 </tr>
</table> 

And this is the corresponding Typescript code:

size : number = 5;
board : number[][] = [];

createBoard(){
 this.board = new Array(this.size);
 for(let i=0; i<this.size; i++){
  this.board[i] = new Array(this.size);
  for(let j=0; j<this.size; j++){
    this.board[i][j] = 0;
  }
 }
}

getImage(i:any, j:any){
  if(this.board[i][j] == 0){
    return "../../../assets/oth/default.jpg";
  } else if(this.board[i][j] == 1){
    return "../../../assets/oth/bidak_hitam.jpg";
  } else {
    return "../../../assets/oth/bidak_putih.jpg";
  }
}

changeImg(i:any, j:any, event:Event){
  if(this.board[i][j] == 2){
    this.board[i][j]  = 0;
  } else {
    this.board[i][j] ++;
  }
}

The issue reported here is that the images are not being loaded. Is there a workaround to fetch image sources using a function in Angular or Typescript?

Answer №1

Instead of using getImage(a,b) as a static string in your code,

<img src="getImage(a,b)" (click)="changeImg(a,b, $event)">

You can dynamically interpolate it by using property binding:

<img [src]="getImage(a, b)" (click)="changeImg(a, b, $event)">

This allows the 'src' attribute to get dynamic data from the getImage function.

Answer №2

Avoid using a function directly in the .html file. Instead, consider creating an array of objects with values and paths as shown below:

this.board = new Array(this.size);
 for(let i=0; i<this.size; i++){
  this.board[i] = new Array(this.size);
  for(let j=0; j<this.size; j++){
    this.board[i][j] = {value:0,path:'assets/oth/default.jpg'};
  }
 }

When changing images within your function, follow this pattern:

changeImg(i:any, j:any, event:Event){
  if(this.board[i][j].value == 2){
    this.board[i][j]={value:0
                      path='assets/oth/default.jpg'}
  } else {
    if (this.board[i][j].value==0)
       this.board[i][j]={value:1
                         path='assets/oth/bidak_hitam.jpg'}
    else
       this.board[i][j]={value:2
                         path='assets/oth/bidak_putih.jpg'}
  }
}

Then, utilize the following code snippet to display the images accordingly:

<img src="board[a][b].path"  
      (click)="changeImg(a,b, $event)">

By implementing this approach, you can avoid unnecessary code execution by Angular.

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

Ways to eliminate Typescript assert during the execution of npm run build?

How can I effectively remove Typescript asserts to ensure that a production build generated through the use of npm run build is free of assertions? Your assistance is appreciated ...

The input does not provide a value for the variable [value]

Having a small issue with using [value] in my input fields. This is the code snippet from my component .html file: <div class="form-group"> <mat-form-field class="example-full-width" style="padding-left: 15px;"& ...

When Ionic Angular app's IonContent scroll element returns an incorrect scrollTop value after navigation completes, what might be the reason behind this unexpected behavior?

In my quest to scroll the ion-content component to the top upon navigating to the page from certain selected pages, I have implemented a solution using the router's NavigationEnd events. However, I have encountered an issue where the IonContent's ...

Django Angular 403 Error: CSRF-cookie not accepted. Reason: CSRF token is missing or incorrect

Currently, I am working on developing a Single Page Application (SPA) with Angular6 integrated with Django. However, I am facing an issue where Django is not accepting the csrftoken cookie that I am sending along with my requests. In my settings.py file, I ...

Unable to successfully import Node, JS, or Electron library into Angular Typescript module despite numerous attempts

I'm still getting the hang of using stack overflow, so please forgive me if my question isn't formulated correctly. I've been doing a lot of research on both stack overflow and Google, but I can't seem to figure out how to import Electr ...

A guide on simulating HTTP methods in Jest when dealing with private methods

I'm grappling with how to simulate the following functionality. I need to simulate both methods: getAllBookInCategory, deleteBookInCategory The public method invokes private methods and I presume I don't need to test private methods, only callin ...

Remove the icon that indicates severity in PrimeNG

Is there a way to eliminate the X icon from the page? <p-message severity="error" text="*" *ngIf="!form.controls['name'].valid "> </p-message> ...

The separator falls short of spanning the entire width of the page

For some reason, I can't seem to make the divider extend to the full length of the page. <TableRow> <TableCell className={classes.tableCell} colSpan={6}> <Box display="grid" gridTemplateColumn ...

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

How to pass an object between two Angular 2 components without a direct connection

My application is structured in the following way. <app> <header> <component-a></component-a> </header> <div> <router-outlet></router-outlet> <component-b></component-b> ...

A different approach to routing in Next.js with getServerSideProps

Let's say I have a dynamic route in my application, with the name [id] Typically, I use getServerSideProps in the pages router to validate any properties passed to the route. It usually looks something like this: export async function getServerSidePr ...

Is it feasible for a React-based shell to host or load an Angular component using Module Federation in Webpack 5?

I am currently developing a web application using Angular that will be embedded or loaded from another web application built with React. I am unsure if this integration can be achieved using webpack 5's module federation. Module federation involves l ...

Strategies for managing unpredictable time series data visualization

I am currently working on graphing data retrieved from an API. You can find a sample of the data here. [ { "id": 10516560, "username": "acrawford69", "avatar_url": "https://a.ppy.sh/1 ...

Is there a way to incorporate my getter into a computed property?

My Vuex Store is built using Vuex module decorators and I am facing an issue with using a getter for a computed property. Here is my code: @Module export default class WorkoutModule extends VuexModule { _workout: Workout; @Mutation startWork ...

How to conditionally make a property optional in Typescript depending on the value of another property

I'm a newcomer to Typescript and I've encountered a scenario that has been difficult for me to find a solution for. Any suggestions would be greatly appreciated. My goal is to have the property options be optional when the type is either SHORT_T ...

Issue with Angualr2: Trying to assign a value to a property of #<AbstractControl> that is read-only

The form structure is as follows: <form [ngFormModel]="myForm" (ngSubmit)="update()"> <ion-label floating>First Name</ion-label> <ion-input type="text" id="fname" [ngFormControl]="fname"> & ...

Next.js TypeScript throws an error stating that the object 'window' is not defined

When trying to declare an audio context, I encountered an error stating that window is undefined. I attempted declaring declare const window :any above window.Context, but the issue persists. Does anyone have a solution for this problem? window.AudioCont ...

"Upon the addition of a child, no response is being given

My database structure resembles the following: https://i.sstatic.net/duWdk.png /* formsById formId usersList userId */ I am trying to retrieve a list of all users (usersList) associated with a specific formId. Below is my method ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...

Enhance TypeScript class declarations with additional properties

Our company has developed its own test framework for our software because we found it difficult to use an open-source framework within the context of our specific development needs. Recently, I took on the task of creating Typescript Definition Files to e ...