Is there a way to modify an image that has been dynamically inserted in an Angular application?

I'm facing an issue with dynamically added input files in Angular. Whenever I upload a file, it changes all the images of the input files instead of just the one I want to target. How can I resolve this problem? Please help.

images = [
      {url: 'assets/images/icons/ico_upload.svg'},
      {url: 'assets/images/icons/ico_cel.svg'}
    ];
    img = this.images[0];
    imgVisible = true;

    fileChangeEvent(event: any, keyName): void {
      this.imageChangedEvent[keyName] = event;

     if(event.target.files.length > 0) 
      {
        console.log(event.target.files[0].name);
       this.img = this.images[1];
  
      }else{
        this.img = this.images[0];        
      }
    }

html code:

<form [formGroup]="filterForm" class="filter-form" (ngSubmit)="Submit()">
                      <ng-container *ngFor="let item of questions2 ">

                          <div *ngSwitchCase="'file'"  >
                              <div class="file">
                                
                                <span class=ellipsis matTooltip="{{item.des}}">{{item.des}}</span><br />
                                <img [src]="img.url">
                                <label>
                                  <input type="file" class="file-upload" (change)="fileChangeEvent($event,'sample')">
                                </label>
                              </div>
                          </div>
 </ng-container>
              </form>

Answer №1

When you bind the image source to a single input field.

<img [src]="img.url">

All items in the list will share the same image source. It might be better to create a separate array of images for each question, Or add a new attribute for each item and bind it to item.imgUrl

<ng-container *ngFor="let item of questions2; let i = index">
<img [src]="item.imgUrl">
fileChangeEvent($event,'sample', i)

And in the component.ts file:

 fileChangeEvent(event: any, keyName, index): void {
 this.questions2[index].imgUrl = this.images[...];

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

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

Using *ngFor with a condition in Angular 4 to assign different values to ngModel

I am new to Angular 4 and encountering an issue with using *ngFor in conjunction with HTML drop-down select and option elements. My categories array-object looks like this - categories = [ { id:1, title: 'c/c++'}, { id:2, title: 'JavaScri ...

The assignment to 'total' is prohibited as it is either a constant or a property that is read-only within the get total() function

After running the command ng build --prod in my project, I encountered the following error message: "Cannot assign to 'total' because it is a constant or read-only property for function get total(){}" The function causing the issue is: get to ...

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Error message: Deno package code encounters error due to the absence of 'window' definition

I am facing an issue with a npm package I imported into my Deno project. The code in the package contains a condition: if (typeof window === 'undefined') { throw new Error('Error initializing the sdk: window is undefined'); } Wheneve ...

Unable to place value into an array following the invocation of a function in Angular 9

Within an array I established, I am encountering an undefined value when I use console.log. Take a look at my component.ts below: export class OrderExceptionReportComponent implements OnInit { public sessionData: ExceptionReportSessionData[] = []; n ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Understanding the process of retrieving form data files sent from Angular to TYPO3/PHP via a Post request

I've been working on uploading an image from Angular to the TYPO3 backend, but I'm struggling to read the request body in the Controller. Here's the code snippet from my Angular side: HTML: <input multiple type="file" (change ...

Unsubscribing from a nested observable - a step-by-step

In our Angular component, we leverage the ngOnDestroy() method to handle canceling http requests that are still pending when navigating away from a page. To avoid reloading data that has already been fetched, we utilize a custom generic cache helper on cer ...

Switch the icon in Angular 2 while using ngFor loop

One issue I am facing with my angular2 project is that the icon does not appear when the page loads, but only after clicking. The array being used is called "keys". <ion-grid class="dueD-line" *ngFor="let line of keys; let i=index"> <div style= ...

Having constant problems with ngModel twoway binding. Any suggestions on how to successfully bind to a property in order to update an api link?

I am attempting to implement two-way binding in order to dynamically change the API endpoint when a button is clicked. The value attribute of the button should be used as part of the API URL string. I tried following an example in the Hero Angular App, bu ...

Searching for a foolproof oauth framework that includes efficient refresh tokens

Currently, I am implementing oauth with refresh tokens for my Angular application and have a specific set of requirements: Automatically refresh the token when 5% of its time is remaining Handle situations where there is a loss of internet connection (re ...

Using React and Typescript: Passing functions as props to other components

In this setup, we have three main components: Toggle, ToggleMenu, and Wrapper. The Toggle component is designed to be universal and used for various functions. The Wrapper component, on the other hand, is meant to change the background color only when the ...

Enhancing Vue prop with TypeScript typing

In my Vue component, I am working with a prop called tabs. The format for this prop is expected to be as follows: [{ id: string title: string color: `#${string}` },{ id: string title: string color: `#${string}` }] Currently, I am utilizing Lar ...

Angular auto-suggestion using Observable

I'm encountering an issue with Angular's autocomplete feature, where I'm having trouble displaying names instead of IDs. You can see the problem in the screenshot here: https://i.sstatic.net/uqk79.png The data is retrieved as an Observable ...

Avoiding the use of destructuring for undefined values in JavaScript can be achieved by implementing

Upon receiving the response registryReportSettings from the server: this.getRegistrySettings(registry.Id).subscribe((registryReportSettings: { extended: ReportPropertiesRequest }) => { const { objectProperties, reportProperties, textProperties } = reg ...

Difference between Angular2 import syntax: "use 'import * as <foo>'" or "use 'import {<foo>}'"

There are two different ways to import modules that I have noticed. Most imports seem to follow this syntax: 'import {<something>} (for example, import { Component } from '@angular/core';) The other way of importing looks like this: ...

Having difficulty accessing custom cells in Angular ng2-smart-table for search functionality

When rendering a "custom" field, one issue that arises is that the global search feature is no longer effective within it. This could be due to the fact that the cell initially appears as a JSON object and then only a single string is rendered from that ...

Utilize devextreme for uploading files

Currently, I am trying to implement an upload document feature using Dev-Extreme, but I keep encountering an error https://i.sstatic.net/dLxWx.png onFileUpload(event){ this.file = event.target.files[0] } <dxi-column [showInColumnChooser]="fa ...