Steps for deleting an image from a component in Angular before getting a new one from API

In my application, there is a child component responsible for fetching and displaying images from an API on the template. The parent component consists of a list of items, and when a user selects an item from the list, a request is made to the API to retrieve the corresponding image. At this point, the child component is rendered, showing the image that belongs to the selected item.

However, I encountered an issue where if the user selects a new item while the child component is already displayed, the previous image remains visible until the new image is fetched from the API. This can be confusing and inconsistent for the user experience.

I am seeking suggestions on how to prevent the display of the previous image and ensure that only the relevant image is shown when a new item is selected. Any insights or advice on achieving this would be greatly appreciated.

Below is a snippet of the parent component template where the child component is invoked:

    <ng-container matColumnDef="expandedDetail">
      <td mat-cell *matCellDef="let element" [attr.colspan]="shownColumns.length">
        <div class="example-element-detail" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
          <div>
            <image-card [img64]="img64"></image-card> -->
          </div>
        </div>
      </td>
    </ng-container>

Child img64 @Input:
@Input()
  public set img64(value: blob) {
    this.loadingData = true;
    if (value) {
      this.image = value.base64Image;
      const objectURL = 'data:image/jpeg;base64,' + this.image;
      this.thumbnail = this.sanitizer.bypassSecurityTrustUrl(objectURL);
    }
  }

Answer №1

To tackle this issue, I addressed the problem by initializing the 'this.image' value to null in both the parent and child components when their functions were executed.

For the parent component responsible for calling the API service:

displaySelectedItem(id: number) { 
    this.selectedImage = null; 
    this.selectedItemService. 
    getItemData(id).pipe(takeUntil(this._unsubscribe$))
    .subscribe((itemImage: ItemImage)=> (this.selectedImage = itemImage)); 
}

Child component:

@Input() 
public set itemImage(value: ItemImage) { 
    this.selectedImage = null; 
    if(value) {
        this.itemImage = value.itemImage
    }
}

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

Transferring data from a child to a parent component in Angular 2 using a combination of reactive and template-driven approaches

Recently delving into Angular 2 ( and Angular overall ) , I found myself at a crossroads with my co-worker. He opted for the template-driven method while I leaned towards the reactive-driven approach. We both built components, with his being a search produ ...

What connections exist between systemjs.config.js and .import() in Angular2/SystemJS?

My journey to learn Angular2 has led me to various Stack Exchange posts and internet articles discussing the function of systemjs.config.js. However, I've noticed that most explanations tend to use the term "app" excessively. For example, when index. ...

"Access to root is necessary for Angular-cli to run smoothly

After installing angular-cli with the command npm install -g angular-cli, I encountered an error every time I attempted to run any ng command. The error message stated: Error: EACCES: permission denied, open '/home/m041/.config/configstore/ember-cli. ...

Invoke a function within a component, within that very component

Hey there, I've got an Angular 2 component with a @HostListener. My goal is to call a method from this component using the @HostListener. Check out the code snippet below for my attempt at implementing this: The Component import { Component, Host ...

How can I effectively make properties accessible in my template to facilitate form validation in Angular?

Scenario: I'm facing a situation in my Angular project where I have a LoginFormComponent. This component has a form with two properties: email and password. My goal is to create properties within this component that can be accessed in the template. Th ...

Where can I find the Cypress.json file for Angular integration with Cypress using Cucumber?

We are currently transitioning from Protractor to Cypress utilizing Cucumber with the help of cypress-cucumber-preprocessor. While searching for Angular documentation on this setup, including resources like , all references lead to an automatically generat ...

Is it possible to add animation to ngFor where the item slides in from the left only when it is within the view port?

I am working with an array containing numerous items. I have implemented ngFor to display only the first few items with a scroll feature. Each item is animated to slide from left into the view port. However, I would like this animation to apply to the bo ...

Is it possible to utilize ion-input's form validation while utilizing an HTML pattern for input?

I am working on validating an ion-input using a regex pattern in the HTML code. The purpose of this is to only allow numbers from 0 to 24 as input. Currently, this validation is functioning correctly and displays an error message if an incorrect number or ...

Exploring the process of connecting to an additional database with Angular Fire

I came across this code snippet: import { FirebaseApp } from "@angular/fire/compat"; import { AngularFirestore } from "@angular/fire/compat//firestore"; import { initializeFirestore } from "@angular/fire/firestore"; impo ...

Steps for assigning the TAB key functionality within a text area

Is there a way to capture the TAB key press within a text area, allowing for indentation of text when the user uses it? ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...

I recently made the switch to Angular 9.0 for my project, but when I ran the build using yarn, I encountered some warnings. Despite the

I encountered this issue on both Ubuntu 16.04 and 18. I have tried various solutions such as reinstalling yarn, node, and clearing the cache, but the warnings persist. For every build using a script, the node_modules folder is deleted and then reinstalled ...

Ways to decrease the node_module size within an Angular application and how to efficiently load Node_Modules directly from the index.html or the root

Looking to decrease the size of node_module (currently 605MB) and load Node_Modules from index.html or application root. Using Angular 5 with node 8.9.4 Various solutions have been attempted but without the desired outcome, npm install --production Git ...

Utilize Firestore for automatic saving of data from Angular Reactive Forms

In my Angular application, I am facing an issue where data entered in a form needs to be instantly saved and updated in a Firestore database. This is crucial because multiple users will be entering data simultaneously on the same form, real-time values are ...

Updating my Angular application using `ng update` did successfully get it to version 11.0.0-next.6. However, I am aiming to revert back

One of my clients has a project using Angular version 8.x.x. I am keen on updating it to the stable version 10.x.x for better performance and features. I followed all the steps mentioned in the Angular update instructions page: https://update.angular.io/? ...

How to Retrieve an Array from a Promise Using Angular 4 and Typescript

I am encountering difficulties when trying to store data from a returned promise. To verify that the desired value has been returned, I log it in this manner: private fetchData() { this._movieFranchiseService.getHighestGrossingFilmFranchises() ...

Angular 2/4: Struggling to refresh child component's view

I need assistance with updating the value of "str" in the child component's view from the parent component. I want to do this by calling the "change()" function in the child component. Here is my code: import { Component } from '@angular/core&ap ...

Angular failing to recognize the && operator

I have a button that opens a dialog with the blockui feature. I am trying to close the dialog and set the blockui boolean variable to false in order to stop blocking the UI. However, in my HTML code (click)="blockedDialog=false && displayAddDialog=false", ...

Can getters and setters be excluded from code coverage reports in Angular projects?

Looking to clean up my coverage reports for the front end portion of an angular project by removing trivial code like getters and setters. I generate my reports using npm run test-sonar -- --coverage, but everything is included in the report when I view ...