Angular dynamic array binding binds to multiple elements rather than just one

In my code, I am working with an array object structured as follows:

let myArray=[
 { "id":"100",
  "child1":[
    {"id":"xx","Array":[]},
    {"id":"yy","Array":[]},
      {"id":"zz","Array":[]}
    ]
 },
 {  "id":"200",
  "child1":[
   {"id":"xx","Array":[]},
    {"id":"yy","Array":[]},
      {"id":"zz","Array":[]}
    ]
 }
  ]

Additionally, I have an Angular template set up like this:

<div *ngFor="let obj of myArray">
    Id:{{obj.id}}
 <div *ngFor="let objChild of obj.Child1">
    Id:{{objChild.id}}
    Array:{{objChild.Array}}    
    AddElementtoArray:<button (click)="add(objChild.Array)">add</button>    
   </div>
 </div>

I also have a method in the Angular component to handle adding elements to the arrays:

add(oArray)
{
oArray.push('xxx');
}

The issue I'm encountering is that when clicking the add button for one ID, values are added to both ID's child arrays. I've attempted filtering based on the index, but it still affects both objects. Any suggestions on how to resolve this would be greatly appreciated.

Answer №1

Consider trying this method where you send the index of both the parent and child elements. This can help you to target a specific element efficiently.

<div *ngFor="let obj of myArray; let parentIdx = index;">
   Id:{{obj.id}}
 <div *ngFor="let objChild of obj.Child1; let childIdx = index;">
   Id:{{objChild.id}}
   Array:{{objChild.Array}}    
   AddElementtoArray:<button (click)="add(parentIdx, childIdx)">add</button>    
 </div>
</div>

Function:

add(parentidx, childidx) {
  this.myArray[parentidx].Child1[childidx].Array.push('xxx');
}

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

Having trouble incorporating Duo Web SDK into angular application

We are currently working on incorporating Duo Two-factor authentication into our Angular application. For instructions, you can take a look at the documentation available here. The issue we are encountering is that their JavaScript file searches for an i ...

Combining Typescript interfaces to enhance the specificity of a property within an external library's interface

I have encountered a scenario where I am utilizing a function from an external library. This function returns an object with a property typed as number. However, based on my data analysis, I know that this property actually represents an union of 1 | 2. Ho ...

Is there a way for me to convert my (TypeScript Definition) .d.ts file into a (JavaScript) .js file?

It seems that there are plenty of guides available on converting a file from .js to .d.ts, but not the other way around. Specifically, I have some code in .d.ts format and I would like to convert it into JavaScript. Can anyone offer assistance with this t ...

An issue occurred with npm resulting in exit code 2. The error is as follows: Command was unsuccessful: node_modules/.bin/vsce package --no

Here is the specific error displayed in cmd: TS1323: Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'. E ...

Encountered an issue with Angular and Ionic 4 when attempting to listen to real-time data: InvalidPipeArgument error was thrown for the AsyncPipe with an empty argument

In my ionic 4 app, I am attempting to implement real-time message updates using angularfire2 and the Firebase Realtime Database. The code snippet is shown below: When running this code, it throws an error: Error: InvalidPipeArgument: '' for pip ...

Encountering ENOENT error: The specified file or directory does not exist, when trying to access 'C:Users itrathodDesktopAngular ode_modules' in an Angular 11 project

Every time I attempt to launch the Angular app, an error message pops up stating the following: An unhandled exception occurred: ENOENT: no such file or directory, lstat 'C:\Users\nitrathod\Desktop\Angular\node_modules' ...

Angular 5 Routerlink and button not working in IE and Firefox due to lack of response

Recently, I created a new Angular 5 CLI application and developed a navmenu component for the top section of the app. It functions flawlessly in Edge and Chrome - clicking on menu items follows the specified route in app.module.ts as expected. However, whe ...

Is it possible to deactivate the click event on an Angular mat table row?

Within my Angular mat table, I have implemented code that expands a table row when clicked. However, I now need to prevent certain rows from being clickable based on the "element.disable" property. <ng-container matColumnDef="id"> <th mat-hea ...

Using a decorator with an abstract method

Discussing a specific class: export abstract class CanDeactivateComponent { abstract canLeavePage(): boolean; abstract onPageLeave(): void; @someDecorator abstract canDeactivateBeforeUnload(): boolean; } An error occurred stating that A decorat ...

Incorporate @ngx-translate into individual components within Angular 17 for enhanced translation capabilities

I have encountered an issue while using standalone components in Angular 17. Interestingly, when I used module architecture, this problem did not arise. By adding the necessary import to 'AppModule', everything worked perfectly. imports: [ Trans ...

What is the ideal method to manage API post requests in Angular?

I have a requirement to search for a document based on its name property by providing a string input from my Angular application. This involves calling a REST API endpoint with a function that resembles the following code snippet: exports.idea_search = f ...

What is the best way to extract specific fields from nested tables using MikroORM?

I am currently facing challenges while attempting to extract specific fields from nested join results. Within my entities, there is a "Restaurant" entity that has a one-to-many relationship with "Product". Each "Product" has a many-to-many relationship wi ...

Is there a way to identify which elements are currently within the visible viewport?

I have come across solutions on how to determine if a specific element is within the viewport, but I am interested in knowing which elements are currently visible in the viewport among all elements. One approach would be to iterate through all DOM elements ...

Elevate your AngularJS directive by incorporating ngModel into an Angular component

Attempting to switch my AngularJS directive over to an Angular Component. Below is the original code for the directive: ng1AppModule.component('ng1Tmp', { bindings: {p: '<'}, require: {ngModel: 'ngModel'} }); Her ...

Checking dynamic controls for validity

In my Angular application, I have a table nested inside a form tag. This table consists of a text box and a dropdown menu. I want to implement validation for these elements, so that an error message is displayed if the user leaves them empty or doesn' ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...

Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far: function customFunction<T = any>(input ...

Tips on adjusting the text color of the material radio button

Looking for some assistance here. I'm working with a small piece of code that combines Material UI and Angular. I have a radio button group where the text color is not changing, despite setting the SCSS value to #262D34. <mat-radio-group aria-label ...

Error: Unable to access the 'next' property of null within an Angular 2 Observable

Issue Found An error of type TypeError has occurred: Cannot read property 'next' of null Problematic Template Utilizing Observer.next import { NavService } from '../../providers/services/nav-service/nav-service'; @Component({ ...

Ionic 3 Local Notification spamming a particular page with excessive pushes

Recently starting out with Ionic, I encountered an issue while developing a basic app that should display a specific page by opening a Local Notification. The problem arises when I create multiple notifications – after clicking on the second notification ...