Tips for utilizing ngModel within *ngFor alongside the index?

Currently, I am dynamically generating mat-inputs using *ngFor. My goal is to store each value of [(ngModel)] in a separate array (not the one used in *ngFor) based on the index of the *ngFor elements. Here's my implementation:

<div  *ngFor="let item of items; let id = index;">

<mat-form-field>
  <mat-select [(ngModel)]="differentArray[id].first" (ngModelChange)="onSelection()">
    <mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
  </mat-select>
</mat-form-field> 

<mat-form-field>
  <mat-select [(ngModel)]="differentArray[id].second" (ngModelChange)="onSelection()">
    <mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
<mat-select [(ngModel)]="differentArray[id].third" (ngModelChange)="onSelection()">
<mat-option *ngFor="let number of arrayOfNumbers"[value]="number"> {{number}} </mat-option>
</mat-select>
</mat-form-field>

</div>

However, I've noticed that all the values for different *ngFor loops end up being the same. Why is this happening and what can be done to properly differentiate them based on element id?

Answer №1

According to the property bindings and [(ngModel)] directives you've defined, the structure of differentArray should be as follows:

differentArray = [
  { first: 0, second: 0, third: 0 },
  { first: 0, second: 0, third: 0 },
  { first: 0, second: 0, third: 0 }
]

For a working example, refer to this Stackblitz link.

Update

Instead of pushing it in the parent component, you can bind the @Input() decorator to a setter and directly initialize the differentArray in the child component. Whether you handle it in the parent or child, remember that objects will be pushed by reference. Therefore, any changes made to one object will affect others. To avoid this, use JSON.parse(JSON.stringify(obj)) to create deep clones. Here's an example:

parent.component.ts

export class ParentComponent {
  items = ['item1', 'item2', 'item3'];
  arrayOfNumbers = [1, 2, 3, 4, 5];
  differentArray = { first: 0, second: 0, third: 0 };

  constructor() {}
}

parent.component.html

<app-child [items]="items" [arrayOfNumbers]="arrayOfNumbers" [differentArray]="differentArray"></app-child>

child.component.ts

export class ChildComponent {
  _differentArray: Array<any> = [];

  @Input() items: Array<any> = [];
  @Input() arrayOfNumbers: Array<any> = [];
  
  @Input() set differentArray(obj: any) {
    this.items.forEach(item => 
      // Deep cloning using `JSON.parse(JSON.stringify(obj)` here
      this._differentArray.push(JSON.parse(JSON.stringify(obj)))
    );
  }

  constructor() {}

  onSelection() {
    console.log('selected: ', this._differentArray);
  }
}

child.component.html

<div *ngFor="let item of items; let id=index;">
  <mat-form-field >
    <mat-select  [(ngModel)]="_differentArray[id].first"  (ngModelChange)="onSelection(id)">
      <mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
    </mat-select>
  </mat-form-field> 

  <mat-form-field>
    <mat-select  [(ngModel)]="_differentArray[id].second"  (ngModelChange)="onSelection(id)">
      <mat-option *ngFor="let number of arrayOfNumbers" [value]="number" >{{number}}</mat-option>
    </mat-select>
  </mat-form-field>

  <mat-form-field >
    <mat-select  [(ngModel)]="_differentArray[id].third"  (ngModelChange)="onSelection(id)">
      <mat-option *ngFor="let number of arrayOfNumbers" [value]="number">{{number}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

For a demonstration, visit this Stackblitz link.

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

Is there a way to incorporate the "Handoff to Human" feature in a Microsoft Teams bot app by utilizing the Teams Toolkit? Can this functionality be implemented using TypeScript?

Can someone assist me with figuring out how to incorporate the "handoff conversation to human agent mechanism" in my project using TypeScript, Microsoft Bot Framework, and Teams Toolkit? ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

"Discovering the root cause of Angular memory leaks and resolving them effectively is crucial for

I am facing an issue with a code that appears to be leaking, and I am seeking advice on how to identify the cause or properly unsubscribe. Even after adding an array containing all object subscriptions, the memory leakage persists. import { Component, On ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

https://i.sstatic.net/KoGto.png Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script ...

Is there a way to use openapi-generator with typescript-angular to generate just a module within an existing Angular project instead of creating a separate package?

Currently, I am utilizing the openapi-generator tool specifically for typescript-angular. Although I have been able to successfully generate an Angular module along with all its components, it results in a separate npm package. While I acknowledge the ad ...

The error was thrown by the internal module loader in Node.js at line 1029

I encountered this Console Error - "Error: Cannot find module". Below is the detailed error message in the console. Any solutions? node:internal/modules/cjs/loader:1029 throw err; ^ Error: Cannot find module '/home/hiranwj/list' at Mo ...

My custom styles no longer seem to be applying after upgrading Angular Material from version 14 to 15. What could be causing this issue

Having some challenges with the migration from Angular 14 to Angular 15 when it comes to overriding material UI elements and themes. Looking for blog posts or documentation that can provide guidance on how to smoothly transition. Specifically, experiencin ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

The Firebase Cloud Function is failing to trigger on the onCreate event within the Firebase Realtime Database

I recently deployed a function to Firebase with the following code: import * as functions from 'firebase-functions'; import * as admin from 'firebase-admin'; console.log('FILE LOADED'); const serviceAccount = require(' ...

Waiting for a function to complete its processing loop in Angular 7

In my code, I'm dealing with an angular entity called Z which has a property that is a list of another entity named Y. My goal is to delete the entity Z, but before doing so, I need to also delete all the Y entities within it. The challenge arises fro ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Steps for implementing a conditional rendering in your codeHere is a

I've encountered an issue while attempting to implement conditional rendering. The error I'm getting is Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types&apos ...

Tips for utilizing a particular field in a JSON object as the data origin while employing ng2-completer

As a newcomer to Angular and ng2 completer, I am working with an array of objects structured like this: var concepts = [ { id:, code:, concept:, display: } ............ ] The goal is to have the data source for auto suggest feature as the di ...

Guide to implementing basic authentication within an HTTP request in Angular 4

I'm new to this and I only have experience with the http post method. I need to send the username and password as base authentication for every API request. onSubmit = function(userdata){ this.tokenkey = localStorage.getItem('logintoken&apos ...

Using Typescript to pass an interface as an argument to a function that requires a JSON type

Here is an extension related to the topic of Typescript: interface that extends a JSON type Consider the following JSON type: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} The goal is to inform type ...

Why isn't the constraint satisfied by this recursive map type in Typescript?

type CustomRecursiveMap< X extends Record<string, unknown>, Y extends Record<string, unknown> > = { [M in keyof X]: M extends keyof Y ? X[M] extends Record<string, unknown> ? Y[M] extends Record<st ...

Finding a solution to the dilemma of which comes first, the chicken or the egg, when it comes to using `tsc

My folder structure consists of: dist/ src/ In the src directory, I have my .ts files and in dist, I keep my .js files. (My tsconfig.json file specifies "outDir":"dist" and includes 'src'). Please note that 'dist' is listed in my git ...

When clicking the button, the service function is not properly updating the view

Upon calling this.getLeaderboard(); in the ngOnInit() function within leaderboard.component.ts, the leaderboard is only displayed on page load or refresh, which is expected. However, I also want to retrieve and display the leaderboard upon clicking a butto ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...