Dynamic row generation with dropdown menu and data binding

Currently, I am working with a table that dynamically creates rows containing details of uploaded files. Each row includes a dropdown menu for selecting the file type.

The issue I am encountering is with the dynamically generated dropdown menus. If I select a value in one dropdown, it sets the same value for all dropdowns in all rows.

Here is the HTML code:

<table>
 <thead>
  <tr>
   <th>File Name</th>
   <th>File Type</th>
  </tr>
 </thead>

 <tbody>
  <tr *ngFor="let item of uploader.queue">
   <td>
    {{ item?.file?.name }}
   </td>

   <td>
    <mat-form-field>
      <mat-select  placeholder="Select File Type" [(ngModel)]="selectedType">
        <mat-option *ngFor="let type of Types" [value]="type.type">
          {{type.type}}
        </mat-option>
       </mat-select>
     </mat-form-field>
   </td>
   <td>
    <button (click)="AddPdf(item)">Upload</button>
   </td>
  </tr>
 </tbody>
<table>

In my TypeScript file:

public AddPdf(Filenames: FileItem) {
  this.data = { filename: FileNames.file.name.toString() , LetterName:this.selectedLetterName, LetterType: this.selectedType };
  console.log(this.data.filename, 'File Name');
  console.log(this.data.LetterName, 'Letter Name');
  console.log(this.data.LetterType, 'Letter Type');
}

When I add three files, three rows are generated. However, if I choose the file type for one row, it applies to all rows. I need help understanding and fixing this issue!

Your assistance will be greatly appreciated.

Answer №1

After some troubleshooting, I managed to solve the issue. Instead of using [(ngModel)], I decided to split it into two separate parts like this:


<mat-form-field>
  <mat-select
    placeholder="Select Letter Name"
    #lettername
    [ngModel]="selectedLetterName"
    (ngModelChange)="onLetterNameSelect($event)"
    [ngModelOptions]="{standalone: true}">
    <mat-option *ngFor="let LetterName of LetterNames" [value]="LetterName.ReportName">
      {{LetterName.ReportName}}
    </mat-option>
  </mat-select>
</mat-form-field>

It worked perfectly after implementing this change.

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

The combination of Stripe, Angular, and TypeScript is not compatible

Attempting to utilize Stripe.card.createToken() in order to generate a token for backend usage has proven to be challenging. Integrating this functionality with Angular and TypeScript requires careful coordination. Currently, the angular-stripe and stripe. ...

Exploring the method of subscribing to streams in Angular2

I have a streaming web-service running on localhost:8080/stream that responds whenever a new message is added to the subscribed mqtt stream. I am looking to integrate this web-service into my Angular2 app using RxJS to consume NodeJS APIs. The code snipp ...

Is the state variable not being properly set by using React's setState within the useCallback() hook?

Within a React FunctionComponent, I have code that follows this pattern: const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => { const [someStateObjVar, setSomeStateObjVar] = React.useState({}); const [ ...

FormArray in Angular fails to recognize the inputs for form controls in the last element

I am currently trying to create a FormArray with multiple FormGroups, but I am encountering a strange issue. The FormControls present in the last element of the FormArray are not accepting input values. add-modules.ts file import { ChangeDetectorRef, Comp ...

What is the method for showing a collection of items divided by commas on the console screen?

I am struggling to format my data output in the console. I want it to look like this: [ {id: 1, text: 'Sentence 1'}, {id: 2, text: 'Sentence 2'}, {id: 3, text: 'Sentence 3'}, {id: 4, text: 'Sentenc4 &ap ...

Determine the exact Angular TemplateRef within a QueryList

Within Angular 6/7, I am facing an issue with a component where I am projecting content such as (ParentComponent template): <my-component [templateNames]="['t1', 't2']"> <ng-template name="t1">...</ng-template> &l ...

In Typescript Angular, how can I invoke a function on each element of an array as part of a sequence of Observables, and then return the total number of successful operations?

I am faced with the task of creating a parent record followed by multiple child records (order does not matter), and ending with a logging action. I am knowledgeable on how to chain single actions on an observable by mapping them together. For example: - ...

The circular reference error message "Redux Action 'Type alias 'Action' circularly references itself" appears

I am currently working with two different actions: export const addToCart = (id: string, qty: number) => async ( dispatch: Dispatch, getState: () => RootState ) => { const { data }: { data: IProduct } = await axios.get(`/api/products/${id}`) ...

The lack of space within the <mat-select> component is causing some issues. Is there a way to incorporate multiple lines within the <

Is there a way to display multiple lines of text for each option in mat-select, instead of limiting the characters and adding "..." at the end? I need the options to have additional description lines. Here is a StackBlitz demo showcasing my issue: https:// ...

A guide on how to retrieve an observer from localStorage or another observer in Angular2

Can anyone help me with my "loantype" service get() function: get() { return new Observable(observer => { let response; if ( localStorage.getItem('loantypes_are_valid') === '1' ) { response = JSON.parse(localStorage. ...

Filtering the JSON data shown according to an array in Angular 7

After receiving JSON data from the backend using a service, I am displaying it through a loop in main.html. There is an array that contains the values of a column being displayed. For example, if the array looks like this: colors=[red,blue], then only reco ...

Using the ternary operator will always result in a TRUE outcome

Having trouble with a ternary operator expression. AssociatedItemType.ExRatedTag ? session?.data.reloadRow(ids) : this.reloadItemRows(this.prepareItemsIdentities(ids)!), The AssociatedItemType is an enum. I've noticed that const ? 1 : 2 always retur ...

What is the best method for inserting content into a custom element as input for the component?

Currently, I am in the process of creating a syntax highlighting web component that will be able to highlight any content placed inside it. Let me illustrate with an example code snippet: <fs-highlight data-line-numbers="true" data-language=&q ...

Toggling multiple ions simultaneously does not function independently

I encountered a problem while working on an ionic app. I needed to have individual control over toggle switches, but my current code toggles all switches at once whenever one switch is tapped. Is there a way to fix this and manage each toggle switch separa ...

Angular 2 issue: ControlValueAccessor failing to detect changes

I've followed a tutorial and implemented ControlValueAccessor in my component. However, it seems that the changes to the ngModel are not being detected within the component. Did I overlook something? import { Component, OnInit, forwardRef } from &apo ...

Issue with encapsulation in NG Bootstrap

Having an issue with ng-bootstrap (v7.0.0) and Angular (v10) integration. I am struggling to encapsulate Bootstrap within a specific component while using an accordion from ng-bootstrap. The CSS only works when I include @import "~bootstrap/scss/boot ...

When activating SSR in the Urql client, I encountered the following unexpected error: Server HTML should not include an <a> within a <div>

Unexpected Error Encountered while Rendering HTML at div at Styled(div) (Emotion Element) at div at Styled(div) (Emotion Element) at Flex (Chakra UI) at NavBar (Navigation Bar) at Index (Homepage) at withUrqlClient(Index) (Urql Client) at ColorModeProvider ...

Using TypeScript with React - employing useReducer with an Array of Objects defined in an Interface

After implementing the given component, I encountered an error related to my useReducer function. The specific error message states: "No overload matches this call..." and provides details on how the parameters are not compatible. import React, {useReducer ...

Unable to load class; unsure of origin for class labeled as 'cached'

Working on an Angular 10 project in visual studio code, I've encountered a strange issue. In the /app/_model/ folder, I have classes 'a', 'b', and 'c'. When running the application in MS Edge, I noticed that only classes ...

ngFor directive not iterating properly without any errors being displayed in the console

I reviewed numerous inquiries about issues with "ngFor not functioning properly". Here are the specifics. app.modules.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; impo ...