Leveraging ngModel within Form Arrays in Angular 4 with ReactiveFormsModule

While working with simple array forms in Angular 4, I encountered an unusual problem with ngModel 😢.

Take a look at my code first.

My Approach

  1. Defining my form FormGroup:

    public invoiceForm: FormGroup;
    
  2. Setting my testing Data and Form Model:

    readonly local = [
    'Lorem ipsum dolor sit amet',
    'et iusto odio dignissim qui blandit',
    'Epsum factorial non deposit',
    'Ma quande lingues coalesce'
    ];
    public localModel = this.local;
    
  3. Define form group in ngOnInit and simply add my locals row into the form group:

    this.invoiceForm = this._fb.group({
        itemRows: this._fb.array([this.initItemRows()])
    });
    
    
    for (let index in this.local)
        this.setAndReplaceNewERow(+index)
    

Initially, everything seems correct. See result as image

The Issue

When I change one of the text inputs, the main variable also changes.

Before Change :

FormGroup
{
  "itemRows": [
    {
      "itemname": "Lorem ipsum dolor sit amet"
    },
    {
      "itemname": "et iusto odio dignissim qui blandit"
    },
    {
      "itemname": "Epsum factorial non deposit"
    },
    {
      "itemname": "Ma quande lingues coalesce"
    }
  ]
}

My Local Data
[
  "Lorem ipsum dolor sit amet",
  "et iusto odio dignissim qui blandit",
  "Epsum factorial non deposit",
  "Ma quande lingues coalesce"
]

My Form Model
[
  "Lorem ipsum dolor sit amet",
  "et iusto odio dignissim qui blandit",
  "Epsum factorial non deposit",
  "Ma quande lingues coalesce"
]

After change :

FormGroup
{
  "itemRows": [
    {
      "itemname": "Lorem ipsum dolor sit amet"
    },
    {
      "itemname": "et iusto odio dignissim qui blandit"
    },
    {
      "itemname": "changed !!!!!!!!!!!"
    },
    {
      "itemname": "Ma quande lingues coalesce"
    }
  ]
}
My Local Data
[
  "Lorem ipsum dolor sit amet",
  "et iusto odio dignissim qui blandit",
  "changed !!!!!!!!!!!",
  "Ma quande lingues coalesce"
]
My Form Model
[
  "Lorem ipsum dolor sit amet",
  "et iusto odio dignissim qui blandit",
  "changed !!!!!!!!!!!",
  "Ma quande lingues coalesce"
]

DEMO

Please check out the Plunk Demo

Answer â„–1

If you want to keep your readonly local variable unchanged, here's what you need to do:

Instead of:

public localModel = this.local;

Use this:

public localModel = Object.assign({}, this.local);

Explanation: By assigning your localModel the same reference as your local variable, any changes made in the form will affect both variables. Using Object.assign() creates a copy of the value, giving you a new reference.

Note: If you are dealing with arrays, you may encounter similar issues. In such cases, consider making a Deep Copy to create a new reference for the array and its values.

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

Encountered a PrismaClientValidationError in NextJS 13 when making a request

I am currently working on a school project using NextJS 13 and attempting to establish a connection to a MYSQL database using Prisma with PlanetScale. However, when trying to register a user, I encounter the following error: Request error PrismaClientValid ...

Generate a series of HTTP requests using an HTTP interceptor

Is it possible to initiate an http request before another ongoing http request finishes (For example, fetching a token/refresh token from the server before the current request completes)? I successfully implemented this functionality using Angular 5' ...

I'm having trouble sending my token to the header because my app is not storing it correctly

Upon implementing validaToken() at login, I encounter the following error even though the token is correctly stored in local storage. I have tried putting it on the server side, but unfortunately, it does not seem to work: server.app.use( bodyParser.urle ...

How can I furnish TSC with TypeScript definitions for URI imports in a comprehensive manner?

import Vue from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf7f4">[email protected]</a>/dist/vue.esm.js' If I submit the above code to TSC for compilat ...

When I start the Chrome debugger, my breakpoints do not appear on the screen

Using IDE Visual Studio Code Reviewing tsconfig.json settings: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": t ...

Having trouble uploading a file with Angular and Spring

The issue of uploading files to BE is causing me some trouble. I have been struggling to get it right, even with the code below: Angular service public saveFile(file: File): Observable<any> { const formData = new FormData(); formDat ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

Communication among sub applications is crucial for the success of Micro Frontends

After researching the best practices for frontend applications, I made the decision to refactor our monolith application. Instead of choosing between micro frontends and mono repo approaches, I decided to merge them both in a unique way. I plan to create ...

Using a For Loop in VueJS with TypeScript for an array of objects

I'm currently working on a for loop within an object array. Below is the code snippet I am working with: private async rightsOverview() { let item: any[] = []; const prod = await fetchFromApi<ProductionBaseType>(`/productions/${id ...

Is there a way to append a unique property with varying values to an array of objects in TypeScript?

For instance: items: object[] = [ {name: 'Backpack', weight: 2.5}, {name: 'Flashlight', weight: 0.8}, {name: 'Map', weight: 0.3} ]; I prefer the items to have an 'age' property as well: it ...

Filtering strings with the same suffix

Here is a code snippet I am working with: type RouterQuery = keyof AppRouter['_def']['queries']; This code defines the following type: type RouterQuery = "healthz" | "post.all" | "post.byId" | "catego ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

Displaying the Ionic loading spinner on the entire page rather than a restricted small box

Right now, I'm able to implement a basic loading effect, but it appears as a small box. presentCustomLoading() { let loading = this.loadingCtrl.create({ content: 'Loading Please Wait...' }); loading.present(); } However, I ...

Eliminate special characters from a string using Protractor

I am currently in the process of writing protractor tests for my angular application. One particular test case that I am working on involves comparing a span value before and after clicking a button. it('Compare dollar values', function () { ...

The process of removing and appending a child element using WebDriverIO

I am trying to use browser.execute in WebDriverIO to remove a child element from a parent element and then append it back later. However, I keep receiving the error message "stale element reference: stale element not found". It is puzzling because keepin ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

Adapting the current codebase to be compatible with Typescript

Currently, my codebase is built with redux, redux-saga, and react using plain Javascript. We are now considering incorporating Typescript into the project. Some questions arise: Can plain Javascript files coexist with tsx code? I believe it's possibl ...

Issues with the messaging functionality of socket.io

Utilizing socket.io and socket.io-client, I have set up a chat system for users and operators. The connections are established successfully, but I am encountering strange behavior when it comes to sending messages. For instance, when I send a message from ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...