Inconsistency in setting values within Angular Bootstrap Modals

Update 2

<div *ngFor="let c of uiVideos;let i= index" class="row curriculum-single">
    <button style="display:none" data-toggle="modal" data-target="#videoReplace"></button>
  <app-upload-modal [id]="i" ></app-upload-modal>
</div>

Update 1: Here is my upload-modal.ts

... Content shortened for uniqueness ...

In component ts following code determines the modals videosToBeReplaced value

OpenUploaderAndBindContent(c: UIVideo) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);
    
    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger').click();
  }

Answer №1

Problem

The issue at hand is related to performing operations on the same DOM element during each iteration of a for loop.

Pay attention to your OpenUploaderAndBindContent function.

OpenUploaderAndBindContent(c: UIVideo) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);

    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger').click(); <-- ISSUE 1
  }

You are triggering the same button for each video, leading to attempts to open the same modal. This occurs because the button targets the same modal with id=videoReplace. Refer to the snippet below where the button targets videoReplace.

<button id="videoReplaceTrigger" style="display:none" data-toggle="modal" data-target="#videoReplace"></button>
<div class="add-popup modal fade" id="videoReplace" #videoModal tabindex="-1" role="dialog" aria-labelledby="videoReplace"  >

Solution

To solve this issue:

  1. Avoid targeting the same button and modal by their id.
  2. Create multiple modals, one for each video, using a new modal component named modal-component.
  3. Move the modal content into this new component.

Make the button and modal id dynamic by utilizing @Input.

  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header gredient-bg">
        <ul class="card-actions icons right-top">
          <li>
            <a href="javascript:void(0)" class="text-white" data-dismiss="modal" aria-label="Close" #closeModal (click)="hideModal">
              <i class="ti-close"></i>
            </a>
          </li>
        </ul>
        <h4 class="modal-title text-center">Replace Video</h4>
      </div>
      <div class="modal-body">
        <div class="package_summary text-center">
          <p>Please upload an MP4 file to replace the existing one. This will replace <strong>{{videosToBeReplaced?.video?.title}}</strong>
          </p>
          <p-fileUpload mode='advanced' #replaceFile name="replace1[]" [url]="getReplaceUrl(videosToBeReplaced?.video?.itemId)"
            accept="video/mp4" maxFileSize="100000000" 
            (onBeforeSend)="onBeforeSend($event)" 
            (onProgress)="onProgressReplace($event)"
            (onSelect)="onFileSelect($event)" 
            (onUpload)="onReplaceVideo($event)" 
            chooseLabel="Select Video">
          </p-fileUpload>
        </div>

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

4.Use the modal-component inside the for loop

<div *ngFor="let c of uiVideos;let i= index" class="row curriculum-single">
   <modal-component [id]="i" ></modal-component>
</div>

Note: The modal-component has an input for id, which generates dynamic ids for the modal and button.

5.The revised method should look like this:

OpenUploaderAndBindContent(c: UIVideo, index:number) {
    console.log('before c: ' + c.video.itemId + ' - ' + c.video.title);

    this.videosToBeReplaced = new UIVideo();
    this.videosToBeReplaced = c;

    console.log(this.videosToBeReplaced.video.itemId + ' - ' + this.videosToBeReplaced.video.title);
    document.getElementById('videoReplaceTrigger'+index).click(); <-- ID IS GENERATED BY INDEX
  }

This approach dynamically generates ids.

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

What are some ways I can incorporate PrimeNG components into my Ionic 4 project?

Exploring the integration of PrimeNG components in an Ionic 4 application is my current project. The initial steps I took included creating a blank Ionic 4 app: ionic start myApp blank Afterwards, I proceeded to download PrimeNG into the project: npm ...

Setting the value of a dropdown menu by updating a form

Currently, I am utilizing a select element with Angular: <select class="form-select form-select-md" formControlName="MaritalStatus"> <option value="0" selected>Select...</option> <option *ngFor=&qu ...

Trouble with z-index property within the confines of the <ion-segment-button></ion-segment-button> tag

The z-index property seems to be having no effect on the elements within the ion-segment-button. I attempted to adjust the positions of the elements and set the z-index to 999999 with the button z-index set to -1. However, this solution did not work as ex ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

Employing the reactive forms approach for validation instead of ngModel logic

Exploring the realm of Angular's form validation, I find myself torn between two routes. However, I am on a quest to merge the strengths of each and reach a solution that resonates with me. Delving into the technicalities, I come across the FormBuild ...

Action buttons on material cards extend beyond the boundaries of the card content on both the left and right sides

Check out this Angular 10.2 Material sample where the action buttons on the right and left extend beyond the card-content: https://i.sstatic.net/Btxy1.png The "Create account" button's right edge should align with the right edge of the fields, and t ...

User instance does not function with the binding

When text is entered into the text box, the Angular form value changes but the userModel value remains the same , always displaying [Vino] as the userModel value. Below is the code from app.component.html, <form #userForm="ngForm"> {‌{userFor ...

An issue has occurred in my deeply nested reactive form where I am unable to read the properties of null, specifically the 'controls' property

I have encountered an issue with a deeply nested form that communicates with a REST endpoint upon submission. While the first two levels of the form are functioning properly, I am facing numerous challenges when trying to work with the third level. One par ...

Unit Testing Angular Components: A guide on instantiating components with constructors that require Globals.ts file as an argument

I'm currently in the process of writing a unit test for my Angular 6 application's Login Component. In the login.component.ts file, there is a constructor that looks like this: constructor(public global: Globals, private appService: AppService) { ...

Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table. However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome w ...

In TypeScript version 2.4.1, the fontWeight property encounters an error where a value of type 'number' cannot be assigned to the types of '"inherit", 400'

When attempting to set the fontWeight property in TypeScript, I encounter the following error: Types of property 'test' are incompatible. Type '{ fontWeight: number; }' is not assignable to type 'Partial<CSSProperties>&a ...

The OutDir in TypeScript is populated with the package.json file

Currently, I'm in the process of developing a simple npm package and everything seems to be going smoothly. However, there is an issue that arises when attempting to build it. Upon building, the structure looks like this: - dist - package.json ...

Using ngFor to display images with src attribute, merging information from two different properties within the loop

One issue I am facing involves an array with properties: export interface IGameTag{ name: string; relativePath: string; filename: string; } I understand that it is possible to include the filename in the relativePath like this: <div *ngFor=" ...

How can I preserve data in editable PDFs with Angular and JavaScript?

Need help with savedoc() functionality <iframe [src] ="fileurl" #iframe> </iframe> <button (click)="saveDoc()"> </button> Having trouble accessing edited PDF content in Typescript: /*api cal ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

When the typeof x is determined to be "string", it does not result in narrowing down to just a string, but rather to T & string

Could someone help me understand why type narrowing does not occur in this specific case, and return typing does not work without using: as NameOrId<T>; Is there a more efficient way to rewrite the given example? Here is the example for reference: ...

There is no overload match for the HttpClient.get call at this time

I'm trying to set up a file download feature using a blob, but I need to extract the filename from the server's "content-disposition" header. Here's the code I have: const header = {Authorization: 'Bearer ' + token}; const config ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

Include an additional row to accommodate text that exceeds the limit

Is there a way to add an additional row below text in a list? I am utilizing Nativescript, but open to solutions using Angular as well. In my Nativescript (Angular) application, a RadListView is used for displaying a list. When the user clicks on the text ...

Tips for compressing a node.js typescript backend project?

Here's a glimpse of my webpack.config.js file: const path = require('path'); var fs = require('fs') var nodeModules = {}; fs.readdirSync('node_modules').filter(function (x) {return ['.bin'].indexOf(x) === -1;}) ...