Tips for showing a preview of the image chosen in Angular

How can I use Angular to display a preview of the selected image? Currently, when we click, all images are selected. Does anyone have suggestions on how to show the preview of only the selected image and unselect the previously selected one when a new image is chosen?

public images: Array<object> = [
        {
            src: 'https://picsum.photos/250/250/?image=110',
            description: 'Luxury hotel stay',
            price: 250
        },
        {
            src: 'https://picsum.photos/250/250/?image=58',
            description: 'Excursion to discover island animals',
            price: 160
        }
];

HTML:

<div class="image__container" [ngClass]="{ 'selected': selected }">
    <img class="image" [src]="item.src">
<div
    class="image__description"
    (click)="selected = !selected"
>
    <div class="image__description--content">
        <div class="image__description--price">
            {{ item.price }}
        </div>
    </div>
</div>

Check out this Stackblitz for more details.

Answer №1

Thank you for the in-depth query. To resolve the issue, I added a parent property to track the selected row and emitted an event from the child component to update the value. If changes don't reflect, manual change detection can be triggered with this.cdr.detectChanges(). Feel free to review the code snippet provided below and reach out if you have any questions.

import {
  Component,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  ViewChildren,
  QueryList,
} from '@angular/core';
import { GridItemComponent } from '../grid-item/grid-item.component';

@Component({
  selector: 'aer-grid',
  templateUrl: './grid.component.html',
  styleUrls: ['./grid.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class GridComponent {
  currentlySelected;
  @ViewChildren('gridItem') gridItems: QueryList<GridItemComponent>;
  public images: Array<object> = [
    {
      src: 'https://picsum.photos/250/250/?image=110',
      description: 'Luxury hotel stay',
      price: 250,
    },
    // Other image objects
  ];

  constructor(private cdr: ChangeDetectorRef) {}

  updateCurrentlySelected(value: number) {
    this.currentlySelected = value;
    this.cdr.markForCheck();
  }
}

html

<section class="grid-container">
  <ng-container *ngFor="let image of images; let index = index">
    <aer-grid-item
      #gridItem
      [item]="image"
      [index]="index"
      [currentlySelected]="currentlySelected"
      (emitChange)="updateCurrentlySelected($event)"
    ></aer-grid-item>
  </ng-container>
</section>

<br />
<br />

<section>

*ngIf="images && images[currentlySelected] && images[currentlySelected].src" Preview: <img [src]="images[currentlySelected].src" />

Browse stackblitz link

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

Developing customized tools for twitch broadcasters

While exploring the world of streaming, I stumbled upon various widgets like chatboxes and follower goals that piqued my interest. Now, I'm eager to create my own versions. One standout example is the streamlabs widgets. You can tweak the HTML/CSS/JS ...

"Transforming a Java byte array into a ReactJS video: Step-by-step guide

I am getting a file from a Java API server and need to convert it into a video using React JS. The Java API server converts the video file into a byte array using Files.readAllBytes(file) and I need to use this video file byte array to create a video fil ...

The content's div is not extending completely in the horizontal direction

Just starting out with tailwind CSS and struggling a bit with the design aspect due to my lack of CSS skills. Need some assistance troubleshooting my layout, particularly in making sure the div container stretches to fit the screen size properly. https:// ...

The custom styles in Material-Table are taking precedence over all other styling, including Material UI styles, and causing icons to not

I recently started using the Material-Table component for a project I'm working on, and it's been great for managing tables with features like adding, editing, deleting, and searching rows. However, I've run into a few issues that I need hel ...

The function is unable to load all items from the JavaScript data within the CSS modal

Having an issue with my js script. The function portfolioThumb is working correctly as it shows all thumbs, but the function portfolioModal only loads the first element from portfolioData. My modal uses a simple CSS with the :target pseudo-class. Everythin ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Difficulty in pinpointing hyperlinks within a styled list

My current challenge involves customizing the color of links within the <li> elements by applying specific classes to the <li> tag. The structure of my HTML is as follows: <div id="sidebar_tall"> <ul> <li class="active_item"> ...

Text is not wrapping onto a new line following the <hx> elements

I've been struggling to get my paragraph text to start on a new line after the subtitles in my code. I've tried using display:block and adding a right margin to take up the full width of the div, but nothing seems to be working! If you want to s ...

Developing a perpetually scrolling container within a webpage

I am attempting to implement a scrollable div on my webpage that can continuously load content. I am currently using the following code snippet for this --> http://jsfiddle.net/cyrus2013/Qq85d/ $(document).ready(function(){ function loadMoreContent() ...

Improper application of Angular bindings in Chrome when navigating to a page using the browser's back button

Have you encountered this issue before? I have a few textboxes generated within an ngFor loop: <tr *ngFor="let tableRow of lineItems; trackBy:trackByIndex; let rowIndex = index; "> <td class="psavingsSmallerGridCell"><input c ...

Google Maps is experiencing issues with navigating the map accurately

This is a code snippet on jfiddle that I need help with: http://jsfiddle.net/w8NRr/ The issue I'm facing is that when I attempt to move the map, it briefly moves and then returns to its original position automatically. Additionally, the map does not ...

After uploading TypeScript Node package types to NPM, they fail to compile with the error message: "Declaration file for module not found."

I recently shared a new Node package called maps-backend-challenge, on npm (you can find the code on GitHub here). After running npm run build successfully, I proceeded to do npm publish. However, when I tried importing this module into a fresh TypeScript ...

Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance. Currently, I am retrieving data from the back end that has the following structure: { "Airports": { "BCN": { "Arrivals": [ ...

Ways to adjust the size or customize the appearance of a particular text in an option

I needed to adjust the font size of specific text within an option tag in my code snippet below. <select> <?php foreach($dataholder as $key=>$value): ?> <option value='<?php echo $value; ?>' ><?php echo ...

Connecting to Asp.Net Core 6 Signal-R Takes an Unusually Long Time of 4 Minutes

I recently launched a new Asp.Net Core .Net 6 project, integrating a SignalR hub with an Angular 13 client. Although the connection eventually establishes, there is a frustrating delay of 4 minutes before it does. It's worth noting that the applicati ...

Issue with displaying text and aligning content to the left or right in tables on mobile devices

Looking to design a table using Bootstrap and include some pull-left and pull-right content in a column? Check out this code snippet: http://jsfiddle.net/Zoker/sgdfgkvL/ <td> <div class="pull-left">Some content</div> <div cla ...

Eliminate specified text from a group of buttons

My task involves a set of buttons that behave in a specific way when clicked. By clicking on a button, the text "selected" is added to its existing value. If one button is clicked, I want any other buttons with the text "selected" to have this text remove ...

dividing the content of a division into sections similar to a PDF file

I am currently working on a resume application and I am looking for a way to display the HTML preview of the resume in multiple divs or automatically insert a horizontal row if the content exceeds the height of the div. The goal is to make it look like sep ...

Creating a nested/child route structure within the Angular 2 router

Looking to implement nested routing for mypage/param1/1/param2/2 format in the URL. The first parameter is represented by 1 and the second one by 2. It's imperative that there are always two parameters, otherwise an error should be displayed. However, ...

Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers: 'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}' I want to transform it into an array that looks like this: [ {marker: false, value: 'This is&ap ...