Choose a single image by clicking on the <img> tag

While working with Angular, I encountered an issue where rendering multiple images using the img tag resulted in all images changing background color when one of them was clicked. I need to find a solution to change only the background color of the image that is clicked.

Below is the code snippet I am currently using:

html

<img
 [src]="data.Url" alt="image"
 (click)="_upload(data.Url)" 
 [ngClass]="{'green' : toggle, 'red': !toggle}"
>

ts

Within my function:

this.toggle = !this.toggle;
this.status = this.toggle ? 'Enable' : 'Disable';

Answer №1

To handle the rendering of multiple HTML elements, it is assumed that you are utilizing the ngFor directive. In this scenario, you can leverage the index to assign distinct css classes to each element.

Here's an example:

HTML

<div *ngFor="let option of options; let i = index">
 <img
   [src]="option.Url"
   (click)="_upload(option.Url, i)"
   [class.selected]="i === indexSelected" <!--apply the selected css class if condition is TRUE-->
  >
</div>

CSS

.selected {
  background-color: green;
}

TypeScript

...
export class YourComponent {
  indexSelected: number = -1;

  _upload(url: string, index: number) {
    // ...
    this.indexSelected = index;
  }
}

Answer №2

Appreciate everyone, here is the approach I took

<td *ngFor="let item of responseData; let i = index;" (click)="setActive(i)" [ngStyle]="{'background-color': active === i ? '#4b8df2' : 'white' }">
    <div>
    <img 
     [src]="item.Url" alt="image"
     (click)="uploadImage(item.Url)" 
    >
    </div>
</td>

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

Calculate the total amount by multiplying the price and quantity values within nested arrays

I have a collection of objects with nested arrays structured like this [ { orderId: 123, orderStatus: 'Pending', date: 'June 13, 2020', products: [ {product: 'choco', price: 300, qty: 3}, {product: 'm ...

Create a stylish frame around the interior triangle shape

I have created a div containing a triangle shape as shown below: #inner-div { width:200px; height:200px; background-color:black; position:relative; border:2px solid red; } #triangle { border-right:15px solid transparent; border-left:15px s ...

The issue of the HTML email background image not appearing at its full width is

I'm currently working on crafting an HTML email that features two background images within a 600px width layout. Each image is sized at 600 x 786px, and while I've successfully managed to make the first image fill the width of the parent table, ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

Exploring the Four Quadrants of CSS

When I use this fiddle https://jsfiddle.net/8kh5Lw9r/, I am getting the expected four quadrants on the screen. https://i.sstatic.net/O5Q6D.png HTML <div id="one"><p>One</p></div> <div id="two"><p>Two</p></div ...

Separate a tab delimited text file and store it into an array using JavaScript

Looking to parse a text file with tab-separated values in JavaScript and add them to an array? Here's how you can achieve this while excluding the header: Id Symbol 1 A 2 B 3 C 4 D 5 E 6 F 7 G This is what I have attempted so far: va ...

Adding an external JavaScript library to a gateway project: A step-by-step guide

I've been attempting to integrate the Simpl5 JavaScript library into my gateway, but I have encountered some issues. I placed SIPml-api.js and SIPml.js in the webapp/content/scripts directory. In .angular-cli.json, I updated the scripts array as follo ...

Is there a directive in AngularJS that allows for binding HTML templates using ng-bind-html

I'm working on a directive that has the ability to use dynamic templates with expressions inside them. The challenge I face is if I use ng-bind-html, the expression won't be evaluated properly. On the other hand, using ng-bin-template results in ...

Extend child flex boxes vertically when the main axis is horizontal

My flex boxes have the flex-direction set to row and align-items set to stretch. Despite setting align-self to stretch for the child boxes, they only fill the top part of the browser window. Can someone help me troubleshoot this issue? #containerDiv { ...

Dynamic updating in a React application with an express server

Currently, I have set up a boilerplate for a MERN application with an express server on the backend and react on the frontend. My goal is to implement hot reloading in my app so that changes in the react code can be reflected without needing to refresh the ...

What is the best way to calculate checksum and convert it to a 64-bit value using Javascript for handling extremely large files to avoid RAM overflow?

Question: What is the best method for generating a unique and consistent checksum across all browsers? Additionally, how can a SHA256/MD5 checksum string be converted to 64-bit? How can files be read without requiring excessive amounts of RAM when ...

How to use Javascript to set focus on a dropdown list within a PHP script

Having trouble setting focus on the dropdown list in my PHP page dc-test.php, where there are two dropdown lists that are interdependent. The values for these dropdown lists are fetched from a database table. I am unable to set focus on the first dropdown ...

Trouble arises when attempting to modify a property inherited from a parent class in TypeScript while

I've defined a base class like the following: import Vue from "vue"; class ComponentBase extends Vue { constructor() { super(); this.left = 100; this.top = 100; this.isSelected = false; } public left: numb ...

angular table cell with a show more/less button

I'm trying to create a button that can hide/unhide text in a table cell if the length is greater than a certain number. However, the current implementation is not working as expected. The button ends up opening all texts in every cell, and it only wor ...

Combining multiple arrays housed within a single variable

My function retrieves information from multiple APIs with callbacks to one variable (results): function combineObjs(callback) { function partialResult(results) { callback(results); }; searchFlickr.searchFlickr(searchTerm, sea ...

Exploring ways to incorporate or eliminate animations on mobile devices using html/css

Is it possible to control animations on different devices using media queries? For example, can you show an animation only on mobile devices while hiding it on desktop or laptop? Conversely, is there a way to add an animation specifically for mobile device ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

How to change the hover effect of a span with CSS

I am currently attempting to modify the hover effects of my spans. Due to a specific requirement, I find myself needing to assign the same id's to all <li> elements that contain my spans. This results in all of the spans having the same parent i ...

Language setting required for dijit.form.DateTextBox

I am attempting to create a calendar control dynamically using Dojo 1.5 and set the language to Spanish, but so far I have been unsuccessful. I tried using "lang:es-es" among other things with no success... here is the element: <input type="text" const ...

Unable to navigate through bootstrap dropdown items using keyboard shortcuts

I am currently working on a bootstrap dropdown menu that is filled with time zone details. Everything seems to be in order as the dropdown gets populated correctly. However, when I click on it and try to select an item by pressing a key on the keyboard (fo ...