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

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

Properly passing props to child components in React with TypeScript. Resolve Error ts(2322)

I am facing an issue where my code works perfectly in Javascript, but encounters problems when converted to Typescript. Despite the complexity of the question, it actually boils down to a simple query. I just wanted to share the functional JS code as a sol ...

Navigating the correct way to filter JSON data using HttpClient in Angular 4

Struggling with transitioning from Http to HttpClient, here's the code in question: constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) { this.http.get('http://example.com/date.php') .su ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

How can I implement a feature in Angular where clicking the edit button loads a form (in a separate component) pre-populated with previous data, along with an update button for

Within the employee-list component, there is a table displaying a list of employees. This table includes an option to edit details. <button type="button" class="btn btn-primary" routerLink="../create-employee">Edit</b ...

The angular core module is displaying an inaccurate peer dependency warning regarding zone.js

Encountered this error message when trying to update my Angular version: @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e88b879a8da8d9d8c6d9c6dd">[email protected]</a>" has an incorrect peer dependency ...

methods for array filtering in typescript

How do I filter an array in TypeScript? I attempted the following findAllPersonsNotVisited():Observable<Person[]> { var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,"-"); return this.db.list(& ...

Converting React useState to a JSON object data type

I imported a JSON data file using the following code: import data from "../data.json"; The contents of the file are as follows: [ { "name": "Emery", }, { "name": "Astrid", }, { " ...

reactjs: disable a specific eslint rule

I'm trying to figure out how to disable the "no-unused-vars" rule specifically for TypeScript interfaces. Here's a code snippet where I'm getting a warning: export type IKeoTableColumn<T> = { id: T; align: 'left' | ' ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Tips for obtaining the accurate HTML code format using Angular 2's input feature:

I am looking to retrieve all the code with an input as [input] and a tag as #tag. When attempting to obtain HTML code with jQuery using console.log($("#content")[0].outerHTML);, this is an example of how the code looks: <div dnd-droppable [dropZones]= ...

Confirm the presence of a particular sub collection within Firebase/Firestore by returning true

Can you confirm if the sub-collection named 'categories' exists within the users collection in Firestore? Please return true if it exists and false if it does not. ...

What is the most effective method for creating Typescript type predicates that yield the most specific types when filtering arrays?

I believed I had discovered the perfect method for defining predicates: declare function isNumber<T>(x: T): x is Extract<T, number>; declare function isFunction<T>(x: T): x is Extract<T, Function>; ... and so forth This technique l ...

Troubles with Katex/ngx-markdown Display in Angular 16

In my Angular 16 application, I utilize the ngx-markdown library alongside Katex and other dependencies. A challenging situation arises when the backend (an LLM) responds with markdown text that conflicts with Katex delimiters during rendering. I attempte ...

How to Exclude Whitespaces from Strings in Angular 6 DataTables

I am facing a simple issue where I need to display strings with spaces like "st ri ng" in rows within a material data table. However, the spaces are being trimmed and I cannot figure out how to keep them intact. Here is a demo on stackblitz: https: ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Looking for a youtube.d.ts file to integrate the youtube-iframe-api with Angular 2?

My current challenge involves implementing the youtube iframe api for seamless video snippet display and control within an Angular 2 application. Maintaining TypeScript's type concept is crucial for both the webpack compiler and myself :). A brief ov ...

Angular 8 - Customizing primeng/fullcalendar Appearance Based on Event Type (Looping Events) and Cell Background Color

This is how I have integrated fullcalendar into my Angular 8 application: calendar.component.ts: export class MyCalendarComponent implements OnInit { public plantedActivities: PlantedActivityModel[] public actuatorActivities: ActuatorActivityModel ...

How to remove the border of the MUI Select Component in React JS after it has been clicked on

I am struggling to find the proper CSS code to remove the blue border from Select in MUI after clicking on it. Even though I managed to remove the default border, the blue one still persists as shown in this sandbox example (https://codesandbox.io/s/autumn ...