Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows.

https://i.stack.imgur.com/3haZW.png

Current Behavior: Uploading a file in one input updates the value column of all rows.

Expected Behavior: The uploaded file should only appear in the value column of that specific row.

Can anyone provide assistance with this problem? :(

This is the HTML code in my component.html

<div formArrayName="familyMembers">

  <div *ngFor="let group of SonArray;let i = index" [formGroupName]="i">

    <div class="col-xl-12 col-lg-12">

      <!-- another input fields html code -->

      <div class="col-lg-6">
        <div class="row">
          <div class="col-md-12">
            <img id="imagu" class="img-fluid imgo " src="assets/img/4.png" style="text-align: center;justify-content: center;display: flex;margin: auto;width: 250px;height: 200px;" />
          </div>
          <div class="col-md-12" style="margin-top: 5%;">
            <label for="exampleInputEmail">صورة بطاقه الرقم القومى للابن</label>
            <div class="input-group  mb-3">
              <div class="custom-file">
                <input type="file" formControlName="fileImageSonNationalId" accept="image/*" class="custom-file-input" id="fileImageSonNationalId" (change)="HandleFileSonid($event, i)" aria-describedby="inputGroupFileAddon01">
                <label class="custom-file-label upload-lbl" for="fileImageSonNationalId">
                       <span *ngIf="img5 !== null" style="margin-right: 50%;">{{img5.name}}</span>
                        <span *ngIf="img5 === null" style="margin-right: 50%;">اختر صورة</span>
                </label>
              </div>
            </div>
            <div class="text-danger" *ngIf="group.controls.fileImageSonNationalId.touched && img5 === null">
              صورة بطاقه الرقم القومى مطلوبه
            </div>
          </div>

        </div>
      </div>
  </div>
</div>

https://i.stack.imgur.com/eIpoY.png

This is the function to handle files in component.ts

 HandleFileSonid(event: any, index: number) {
    if (event.target.files !== null && event.target.files.length > 0) {
      this.img5 = event.target.files[index];
      const reader = new FileReader();
      reader.onload = function (e) {
        $('.imgo').attr('src', e.target.result);
      }
      reader.readAsDataURL(event.target.files[0]);
    } else {
      this.img5 = null;
      $('.imgo').attr('src', '/src/assets/img/4.png');
    }
  }
https://i.stack.imgur.com/wamfd.png

Initializing formarray in component.ts

 createItem() {
    return this.fb.group({
      name: ['', [Validators.required]],
      nationalId: ['', [Validators.required]],
      phone: ['', [Validators.required]],
      passportNumber: ['', [Validators.required]],
      educationId: ['', [Validators.required]],
      studyId: ['', [Validators.required]],
      birthDate: ['', [Validators.required]],
      mritalStatusId: ['', [Validators.required]],
      genderId: ['', [Validators.required]],
      statusId: ['', [Validators.required]],
      fileImageSonNationalId: ['', [Validators.required]],
      fileImageSonPassPort: ['', [Validators.required]],
      chronic_id21: ['', [Validators.required]],
      prescs1: [false, [Validators.required]],
      operations1: [false, [Validators.required]],
      scan1: [false, [Validators.required]],
      prosthetic1: [false, [Validators.required]],
      physical1: [false, [Validators.required]],
      chronic_id1: ['', [Validators.required]],
      opNameId1: ['', [Validators.required]],
      operCatNameId1: ['', [Validators.required]],
    });
  }

  addSon() {
    (<FormArray>this.userForm.get('familyMembers')).push(this.createItem());
  }
  removeAddress(index) {
    (<FormArray>this.userForm.get('familyMembers')).removeAt(index);
  }
  get SonArray() {
    return (<FormArray>this.userForm.get('familyMembers')).controls;
  }
https://i.stack.imgur.com/aID2V.png https://i.stack.imgur.com/XU1ua.png

Answer №1

The issue at hand arises from utilizing a common selector $('.imgo') to change all images simultaneously across the board. To address this problem, I recommend assigning a unique identifier like:

id="image-preview-{{ i }}"
to each image preview and incorporating it into your code

Below are the necessary components for updating the HTML and implementing the handler:

<img id="imagu"
  id="image-preview-{{ i }}"
  class="img-fluid imgo "
  src="assets/img/4.png"
  style="text-align: center;justify-content: center;display: flex;margin: auto;width: 250px;height: 200px;" />


HandleFileSonid(event: any, index: number) {
  if (event.target.files !== null && event.target.files.length > 0) {
    this.img5 = event.target.files[index];
    const reader = new FileReader();
    reader.onload = function (e) {
      $('#image-preview-' + index).attr('src', e.target.result);
    }
    reader.readAsDataURL(event.target.files[0]);
  } else {
    this.img5 = null;
    $('#image-preview-' + index).attr('src', '/src/assets/img/4.png');
  }
}

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

Guide to dynamically implementing pagination through AJAX calls

In this javascript code snippet, I have a class named PurchaseHistory. var baseUrl = null; var parameters = null; var currentPageNumber = null; var TotalPages = null; var PageSize = null; $(document).ready(function () { baseUrl = "http://localhost/AP ...

Creating Virtual Nodes from a string with HTML tags in Vue 2.5: A Step-by-Step Guide

Having some trouble creating a functional component that displays the Feather Icons package - I'm stuck on the final step. Here's what I have so far: This is my FeatherIcon.vue component. <script> const feather = require("feather-icons"); ...

Exploring Nested Routes and Queries in Vue JS

As a beginner in Vue, I have been exploring a demo project and struggling with understanding how routes with query parameters function. The documentation suggests using router.push({ path: 'register', query: { plan: 'private' }}) to gen ...

Arrange and display similar objects together

I have a list of items in a listView that need to be visually grouped based on their class, displayed within boxes. For example, I have 5 items with the following classes: <div class="1"></div> <div class="1"></div> <div class= ...

What is the best way to adjust the height of a container to equal the viewport height minus a 300px height slider?

Forgive me for the rookie question, I know what I want to achieve should be simple but I seem to be having trouble articulating it in my search for solutions. Essentially, I am trying to set a section in HTML to the height of the viewport minus the height ...

Is there a way to incorporate an MTN Momo or Orange Money payment system into your application if you are not a registered business entity?

Implementing an MTN Momo and Orange Money payment system through their respective APIs is crucial. In addition, I am seeking a dependable and effective method to seamlessly integrate these diverse APIs. During my attempt to incorporate the API via their ...

Implementing relationships in microservices with Prisma and NestJS

Schema for User Management service: model User { id String @id @default(uuid()) username String @unique email String @unique password String } Schema for File Management service: model File ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

What is the best way to choose the next adjacent element using a CSS selector with Python Selenium?

The structure of the DOM is as shown below: <ul> <li> <a href="#" role="button" class="js-pagination link" data-page="1">1</a> </li> <li> <a href="#" role="button" class="js-pagination link active" data ...

Creating a dynamic multi-select feature in AngularJS with ng-repeat

I'm relatively new to AngularJS and JavaScript, but I've managed to create a functional multi-select list. The ng-model linked to the dropdown is part of a "user" DTO object, specifically a property that stores an array of "groups" the user can j ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

What could be causing my dropdown menu to not appear when clicked?

I am trying to implement the functionality shown in the image. When the Settings button is clicked, a window should open allowing the user to navigate to their desired option. However, I am facing an issue where nothing happens when the button is clicked. ...

How can I create a React component that is accessible and controllable from external sources?

Attempting to create a Dialog component using React and Material-UI. Currently, the component behaves like a traditional Material-UI dialog with a button inside the class that opens the dialog. However, I aim to achieve the same behavior as the default Ma ...

Is it feasible to tailor the structure of the new application directory?

Recently, I was assigned a task to explore customizing the folder structure for new apps, specifically Nest apps. After some research, I discovered that it is possible to create a "lib" folder within the "tools" directory and leverage patterns to automatic ...

What could be the reason my custom validator is not functioning properly and how can I troubleshoot it?

I'm currently working on creating an angular reactive form with a unique ID input field requirement. If the submitted ID already exists, I need an error message to display on the angular HTML front end. To achieve this, I am implementing logic to chec ...

Utilizing Angular's capabilities to smoothly transfer objects between controllers

Currently, I am in the midst of developing an AngularJS application integrated with a C# Web API. I have two controllers: A and B. In controller A, there is a list of objects. When I click "Add" (in between two list items), I am redirected to controller ...

What is the best way to place content in a single div without it being divided into several separate boxes

Here is my code snippet: <div class="col-md-9"> <div id="statbox"> {% for obj in product_type %} {% for obj1 in vastu %} <script type="text/javascript"&g ...

Instructions for adding transitions to an entire page in material-ui while maintaining a fixed AppBar

Is there a way to ensure that the material-ui AppBar remains fixed at the top while being wrapped with page contents in a transition? I want the AppBar to transition (e.g. Zoom or Slide) along with the rest of the page contents. I encountered this issue w ...

What is the best approach for managing _app.js props when transitioning from a page router to an app router?

Recently, in the latest version of next.js 13.4, the app router has been upgraded to stable. This update prompted me to transition my existing page router to utilize the app router. In _app.jsx file, it is expected to receive Component and pageProps as pr ...