Whenever I update the values in my input using the ngModel attribute, all of my arrays stored in an object also get updated

I am currently working with a table on the frontend.

<table class="table table-hover">
                <thead>
                    <tr>
                        <th> Account Entry Number </th>
                        <th> Date </th>
                        <th> Account Name </th>
                        <th> Description </th>
                        <th> Debit </th>
                        <th> Credit </th>
                        <th> </th>
                    </tr>
                </thead>

                <tbody>
                    <tr *ngFor="let journalEntry of journalEntries">
                        <td>
                            <input [(ngModel)]="journalEntry.id" type="text" class="form-control" placeholder="id">
                        </td>
                        <td>
                            <input [(ngModel)]="journalEntry.date" type="text" class="form-control" placeholder="Journal entry date">
                        </td>
                        <td>
                            <input [(ngModel)]="journalEntry.account.name" type="text" class="form-control" placeholder="Account name">
                        </td>
                        <td>
                            <input [(ngModel)]="journalEntry.description" type="text" class="form-control" placeholder="Description"></td>
                        <td>
                            <input [(ngModel)]="journalEntry.debit" type="text" class="form-control" placeholder="debit">
                        </td>
                        <td>
                            <input [(ngModel)]="journalEntry.credit" type="text" class="form-control" placeholder="credit"></td>
                        <td>
                            <button (click)="saveJournal(journalEntry)" class="btn btn-primary">
                              <i class="fa fa-save">
                              </i>  
                            </button>
                            <button (click)="deleteJournal(journalEntry)" class="btn btn-danger">
                              <i class="fa fa-trash-o">
                              </i>  
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>

and in the module I have the following:

savePosition( positionEntry: PositionEntry ) {


    this.journalEntry.positionEntries.push( positionEntry );

    console.log(this.journalEntry);

  }

After inserting my first array named "positionEntry" into the object "journalEntry", the object will display these values:

Date: "" ID: "" Position Entries: Array(1) 0: Position Entry account: "2" debit: "2" description: "2" credit: "2" id: 0 proto: Object length: 1 proto: Array(0) user: "" _id: ""

However, when I insert a second value, the old value is overridden by the new one. Furthermore, if I make any changes to the input field, it overrides all arrays in the object "journalEntry". I'm not sure why this is happening, as I've already pushed the data to the object. Why is ngModel linked to the arrays inserted in the object?

Thank you for your assistance.

Answer №1

Give this code a try. It should be functioning correctly after making the following changes:

 <tr *ngFor="let asientoContable of asientosContables; let i = index; trackBy:i;">

Add a name property as shown below:

name="ID-{{i}}"

I have made modifications to your code and used it in the updated version:

<table class="table table-hover">
<thead>
    <tr>
        <th> Numero de Asiento Contable </th>
        <th> Fecha </th>
        <th> Cuenta Contable </th>
        <th> Descripcion </th>
        <th> Debe </th>
        <th> Haber </th>
        <th> </th>
    </tr>
</thead>

<tbody>
    <tr *ngFor="let asientoContable of asientosContables; let i = index; trackBy:i;">
        <td>
            <input [(ngModel)]="asientoContable.id" name="id-{{i}}" type="text" class="form-control" placeholder="ID">
        </td>
        <td>
            <input [(ngModel)]="asientoContable.fecha" name="fecha-{{i}}" type="text" class="form-control" placeholder="Fecha">
        </td>
        <td>
            <input [(ngModel)]="asientoContable.ccontable.nombre" name="nombre-{{i}}" type="text" class="form-control" placeholder="Nombre del asiento contable">
        </td>
        <td>
            <input [(ngModel)]="asientoContable.descripcion" name="descripcion-{{i}}" type="text" class="form-control" placeholder="Descripcion">
        </td>
        <td>
            <input [(ngModel)]="asientoContable.debe" name="debe-{{i}}" type="text" class="form-control" placeholder="Debe">
        </td>
        <td>
            <input [(ngModel)]="asientoContable.haber" name="haber-{{i}}" type="text" class="form-control" placeholder="Haber">
        </td>
        <td>
            <button (click)="guardarHospital( hospasientoContableital )" class="btn btn-primary">
              <i class="fa fa-save">
              </i>  
            </button>
            <button (click)="borrarHospital( hospital )" class="btn btn-danger">
              <i class="fa fa-trash-o">
              </i>  
            </button>
        </td>
    </tr>
</tbody>

Your Component Code should resemble the following:

guardarPosicion( posicionAsiento) {

this.asientosContables.push( new PosicionAsiento(posicionAsiento));

console.log(this.asientosContables);

}

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 default value for the ReturnType<typeof setInterval> in both the browser and node environments

I have a question about setting the initial value for the intervalTimer in an Interval that I need to save. The type is ReturnType<typeof setInterval>. interface Data { intervalTimer: ReturnType<typeof setInterval> } var data : Data = { ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...

Best practices for interacting with a REST API using Angular

I am currently working on a web Angular app where in globalservice.ts I have defined basepath:string = "https://myapi.com/api/v2/". I need to retrieve data from this API. To achieve this, I have included the following code snippet in server.js. Any recomme ...

Tips for setting a default value in a Reactive Form

How can I transfer a default value from HTML to TypeScript using reactive forms? <ul class="list list_2"> <li>Subtotal <span>{{cartTotal | currency:'INR':true:'2.0'}}</span></li> <li>Shippin ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. Here is my HTML code: <section class="favorites"> <div class="category" ...

Transform a JSON array containing individual objects into a new JSON array with objects

My array contains objects with nested objects in each element, structured like this: [ { "person": { "name": "John", "isActive": true, "id": 1 } }, { "person": { "name": "Ted", "isActive": true, "id": 2 } } ] I ...

Angular List Selector: A versatile multiple selection component with a stylish list design

I'm in need of a select component similar to the one shown in The issue is that Material Angular doesn't have this specific component, so I opted to use the default HTML select inside my component. Everything was working fine until I tried to de ...

What is the process for converting variadic parameters into a different format for the return value?

I am currently developing a combinations function that generates a cartesian product of input lists. A unique feature I want to include is the ability to support enums as potential lists, with the possibility of expanding to support actual Sets in the futu ...

How can TypeScript be forced to output a specific data type?

I've created a generic "fetcher" function that is designed to handle different types of entities. However, I'm encountering an issue where TypeScript is inferring the return type based on all possible conditions within the function. Is there a w ...

Why are the inputs and dropdowns not disabled until you press the Edit button as intended?

My HTML file: <div class="main-wrapper" fxLayout="row" fxLayoutAlign="center center"> <mat-card class="box"> <mat-card-header> <mat-card-title>Register</mat-card-title> & ...

Unable to locate template while working with Angular 2 in ASP MVC framework

I am currently utilizing angular 2 within ASP.NET MVC. This particular component is referred to as the "other" component: import { Component } from '@angular/core'; @Component({ selector: 'other-app', templateUrl: './app ...

The CanActivate route guard in Angular Router never seems to return a true value

I'm facing an issue with using CanActivate to protect a page, as it always returns false and I can't access the protected router. Despite trying various solutions, I haven't been able to resolve the problem yet. Being new to angular, I' ...

Determine if a variable contains only one digit in Angular 6 using Typescript

I have a specific value that I want to discuss: this.value.day It gives me a numerical output ranging from 1 to 31. My requirement is to add a leading zero if the number is less than 10. Can anyone guide me on achieving this? ...

Interacting with a form input by triggering the onChange event

I am encountering a problem where I need to be able to select a radio button both onChange via keydown and mouse click. However, I am struggling with accessing both event parameters of the on keydown and on mouse click within the same function. As a result ...

Create an Observable by combining two interconnected sources

I need to combine values from two different Observables into one Observable. The solution is using the zip operator, but my situation is a bit more complex. I have an id for A. A {id, name, idOfRelatedB} //first observable B {...} // second So, in order ...

Error: Missing 1 type argument(s) in generic type definition

I've developed an abstract class structure as shown below: export abstract class CsvFileReader<T> { data: T[] = [] constructor(public file: string) {} abstract mapRow(row: string[]): T read() { this.data = this.file .split(& ...

Ensure that the specified Class type must have a constructor with no arguments

When working with a function that takes a parameter representing a Class (not an object or instance, but the Class itself), or essentially a variable assigned to a Class. The challenge is ensuring that the Class assigned to the parameter has a constructor ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

Is there a method to initiate a 'simple' action when dispatching an action in ngrx?

Here's the scenario I'm facing: When any of the actions listed below are dispatched, I need to update the saving property in the reducer to true. However, currently, I am not handling these actions in the reducer; instead, I handle them in my ef ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...