Link the ngModel input to an object within an ngFor iteration

Looking to create a dynamic form using an array that includes FieldLabel and DataModel references. I want to use the DataModel as an object reference, so when the user updates an input field, the referenced model is updated.

I have searched extensively but haven't found a solution yet. Is there another way to achieve this?

I attempted iterating through the model and used the DataModel attribute in [(ngModel)], but it's treating it as a string instead of referencing the main object.

obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain",
      Address:
        {
          CurrentAddress:"USA",
          PermanentAddress:"Pakistan"
        }
  }

  fields: any[] = [
    {
      "FieldLabel": "First Name",
      "DataModel": "obj.FirstName"
    },
    {
      "FieldLabel": "Middle Name",
      "DataModel":"obj.MiddleName"
    },
    {
      "FieldLabel": "Current Address",
      "DataModel":"obj.Address.CurrentAddress"
    }  
  ];
<div class="container" fxLayout="column" fxLayoutGap="10px">
  <div *ngFor="let field of fields">
    <input placeholder="{{field.FieldLabel | uppercase}}" [(ngModel)]="field.DataModel">
  </div>
  <div>
    <input placeholder="Last Name" [(ngModel)]="obj.LastName">
  </div>
  <br> {{obj|json}}
</div>

My goal is to update the obj with the values entered by the user in the ngFor input fields. Additionally, I am working on generating a complete dynamic form with formulas for each field using this method. Any suggestions for achieving the desired result?

Answer №1

When you create a fields array and utilize DataModel, the original "obj" becomes disconnected from the input. If you choose to take this route, follow these steps [Or check out the following stackblitz - https://stackblitz.com/edit/angular-pdpqog?file=app/app.component.ts]-

obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain"
  }

  fields: any[] = [
    {
      "FieldLabel": "Person Name",
      "property": 'FirstName',
      "value": this.obj.FirstName
    },
    {
      "FieldLabel": "Current Address",
      "property": 'MiddleName',
      "value": this.obj.MiddleName
    } 
  ];

  onChange($event, field) {
    this.obj[field.property] = $event;
  }

<div class="container" fxLayout="column" fxLayoutGap="10px">
  <div *ngFor="let field of fields">
    <input placeholder="{{field.FieldLabel | uppercase}}" [ngModel]="field.value" (ngModelChange)="onChange($event, field)">
  </div>
  <div>
    <input placeholder="Last Name" [(ngModel)]="obj.LastName">
  </div>
  <br> {{obj|json}}
</div>

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

`Using variable names for error checking syntax`

When creating dynamic input fields with a mandatory check inside ngFor, I have used names like field{{idxVar}} where idxVar is the index. However, I am unsure how to properly check for errors using this method. <span [ngClass]="{'active' : fi ...

Using an array as an argument for .map() results in an error

This is quite unusual. Currently, I am passing an array containing a single object to the Render method of a React component: let content = this.state.links.map(link => { // eslint-disable-line return ( <li key={link._id}> <a href ...

Tips on adding a tooltip to the react-bootstrap tab element

How can I add a tooltip to the tabs in my React application using Bootstrap tabs? I have three tabs and I want a tooltip to appear when hovering over each tab. import { Tabs,Tab} from "react-bootstrap"; // inside return <Tabs variant="pills" ...

Preventing JavaScript from refreshing the page when using location.replace for the second time with the identical URL

I've encountered an issue while using location.replace to reload a page that relies on GET variables for displaying a success message. The problem arises when the URL specified in the location.replace call is identical to the current one, causing the ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

The Power of Asynchronous Programming with Node.js and Typescript's Async

I need to obtain an authentication token from an API and then save that token for use in future API calls. This code snippet is used to fetch the token: const getToken = async (): Promise<string | void> => { const response = await fetch(&apos ...

Is there a way to adjust the scrolling speed of a background image to be slower than the rest of

I'm searching for an example similar to this: Are there any efficient javascript solutions available? I've had difficulty implementing the code I've come across so far. ...

Press the toggle switch button to easily switch between two distinct stylesheets

With a looming exam at university, my web design professor has tasked us with creating a website. The unique challenge is to implement a style change by seamlessly switching between two different CSS stylesheets. My idea is to start with a black and white ...

Who is responsible for the addition of this wrapper to my code?

Issue with Sourcemaps in Angular 2 TypeScript App Currently, I am working on an Angular 2 app using TypeScript, and deploying it with the help of SystemJS and Gulp. The problem arises when I try to incorporate sourcemaps. When I use inline sourcemaps, eve ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

Application Path-related Relative Path Problem in MVC Deployment

During the deployment of my MVC Project, I encountered a relative path issue in terms of the server. The project is being hosted as an application in IIS. Once deployed, the URL to access the application will resemble http://localhost/portal/Account/Login. ...

Create an interface that inherits from another in MUI

My custom interface for designing themes includes various properties such as colors, border radius, navbar settings, and typography styles. interface ThemeBase { colors: { [key: string]: Color; }; borderRadius: { base: string; mobile: st ...

What is the best way to ensure that my variables are properly differentiated in order to prevent Angular --prod --aot from causing empty values at runtime?

While testing my code locally in production, the functions I've written are returning the expected values when two parameters are passed in. However, after running ng build --prod --aot, the variable name within the functions changes from name to t. ...

Before users can apply any filters, all items must be loaded into an Observable<Hero[]> array

Is there a way to modify the Angular 2 Tour of Heroes search component so that it displays all items on page load (showing all Heroes) and then makes a new request to get filtered results only when a filter is provided? import { Component, OnInit } from & ...

Storing array data locally within an AngularJS application for seamless sharing between two separate applications

I need assistance with persisting and sharing array data var queries = []; between two separate AngularJS applications. One application is for the front end, while the other is for the admin side. Both applications cause the entire page to load when access ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

Creating a bold portion of a string

My task involves dynamically creating <p> elements within a div based on the contents of my codeArray, which can vary in size each time. Instead of hard-coding these elements, I have devised the following method: for(i=1;i<codeArray.length;i++) ...

It seems that the Angular2-google-maps library is having trouble with installation

Attempting to install the angular2-google-maps library is resulting in errors. The desired library can be found at: The specific error encountered is displayed here: https://i.stack.imgur.com/L2vOY.png Any assistance with this issue would be greatly app ...

How to use plain JavaScript to extract the value from a textarea in GWT

Situation: I am currently developing a tampermonkey script to enhance certain GWT pages within a third-party application. Unfortunately, I do not have access to the source code or servers. Challenge: My task is to retrieve the value of a textarea element ...