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

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Transferring FormArray validators from a child component to a parent component in Angular version 8

UPDATE: I successfully implemented data passthrough and validation by refactoring the email-phone-input.component.ts to utilize ControlContainer, obtain the FormGroup from the parent component, and manage FormArray controls. Stay tuned for the updated repo ...

What is the best approach for unit testing with a subscribe in Angular 5?

import { Component, Input, OnInit } from '@angular/core'; import {DataplansDetails} from '../../models/dataplans-details'; import * as _ from "lodash"; @Component({ selector: 'jsonform', templateUrl: './jsonform.comp ...

Can you explain how to incorporate a node module script into a React.js project?

I have encountered an issue where the element works perfectly fine when using an external node module, but fails to function properly when using a locally downloaded node module. Unfortunately, I am unable to identify the root cause of this problem. You c ...

I am disappointed with the lack of functionality in Angular's HTML type inference

When working inside an Angular component, I want to select a div element by id or class. This method works menuDisplayDiv = document.getElementsByClassName("some_class")[0] as HTMLDivElement; menuDisplayDiv = document.getElementById("some ...

Obtain an array containing various directives in a specific sequence

I am looking to extract directives from the view or content in the exact sequence they were specified in the template. First Attempt [view plunker] @Directive({selector: 'dir-1'}) class Dir1 {} @Directive({selector: 'dir-2'}) class Di ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...

What is the process for importing WebAssembly functions into TypeScript?

I currently have a TypeScript project and am in the process of incorporating a WebAssembly Module to replace certain functionalities. Successfully importing the WebAssembly module involved moving the .wasm loading logic to its own .js file, which is then ...

The error message "NextFunction does not have the property 'render'" appears when using Angular Universal in conjunction with Express

When attempting to implement server-side rendering for my Angular 6 app, I encountered the following error while using the Angular CLI universal demo as a reference: Property 'render' does not exist on type 'NextFunction'. This is the ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Incorporating Paypal subscription functionality and refining subscription challenges

The angular project I'm working on requires configuring a PayPal payment gateway for create subscription, cancel subscription, and upgrade subscription functionalities. I have encountered two issues with PayPal: 1) The PayPal button has been success ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

How can I resolve the issue of "Errors detected in your package-lock.json" in NGRX?

I encountered some problems while trying to set up my Angular project in an NX workspace with NGRX and running it through Jenkins. After running npm install, I started getting errors. Has anyone else experienced errors like these after executing: nx updat ...

Exploring Parquet Files with Node.js

Looking for a solution to read parquet files using NodeJS. Anyone have any suggestions? I attempted to use node-parquet but found it difficult to install and it struggled with reading numerical data types. I also explored parquetjs, however, it can only ...

Implementing conditions in Angular2 router

Here are my current routes: const appRoutes: Routes = [ { path: 'alert/:id', component: AlertDetailComponent }, { path: 'alerts', component: AlertsComponent }, { path: 'dashboard', component: EriskDashboardComponent }, { pa ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with ...

What is the best way to trigger a function in the parent component when a child component is clicked

I'm facing a scenario where I have two components - a parent and a child. Within the child component, there is a button. My goal is to trigger a method in the parent component when the user clicks on that button within the child component. Any ideas o ...

Refine the search outcomes by specifying a group criteria

I have a scenario where I need to filter out service users from the search list if they are already part of a group in another table. There are two tables that come into play - 'group-user' which contains groupId and serviceUserId, and 'gro ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...