Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicated fields if they are not needed.

I attempted to implement this functionality in Angular, and here is some sample code and a Plunker link for reference:

template.ts

<div class="card">
  <input type="text" id="name" value="" class="form-control">
  <label for="form1">Name</label>
  <input type="text" id="mobile" value="" class="form-control">
  <label for="form1">Mobile</label>
</div>

<button type="button" title="Add" class="btn btn-sm" 
(click)="addMore">Add</button>

test.component.ts

export class App {

  addMore() {
    //function to replicate the form input fields
  }

Plunker link: http://plnkr.co/edit/GCCnoMkLynpELwaYX11m?p=preview

Answer №1

If you want to generate dynamic inputs using ngFor, here's how you can do it:

Start by creating an array with an initial value like this,

 inputelements = [{name: '',mobile:''}];

When the user clicks on the "addmore" button, you can add more elements to the array which will then be rendered using ngFor.

The template code should look something like this:

  <div class="card" *ngFor="let word of inputelements; let in=index" class="col-sm-3">
      <div class="form-group">
       <label for="form1">Name</label>
        <input type="text" [(ngModel)]="inputelements[in].name"  class="form-control"  required>
          <label for="form1">Mobile</label>
            <input type="text" [(ngModel)]="inputelements[in].mobile"  class="form-control"  required>

      </div>
  </div>
 <br>
<button type="button" title="Add"class="btn btn-sm pull-right" 
(click)="addMore()">Add</button>

Check out the WORKING DEMO for a live example.

Answer №2

Utilize an array in JavaScript to keep track of inputs and dynamically add or remove them:


inputs = [];

addInput() {
  this.inputs.push(this.inputs.length + 1);
}

See it in action here!

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

Creating a tree structure in JavaScript by parsing a collection of URLs

Hello everyone, I am currently working on creating a dynamic menu list that allows users to create elements without any depth limitations. THE ISSUE The structure of my URLs is as follows: var json_data = [ { "title" : "Food", "path" ...

Bar graph constructed using a pair of div elements

I extracted two values from an array: $target = $data->data[2][32][3]; For this particular example, $target = 9.83%. $clicks = $data->data[1][32][3]; And in this case, $clicks = 7.15%. I have created a bar-like chart using three main div elements ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

What steps do I need to take to set up Vue-CLI 3 to generate a webpage with no JavaScript?

My dilemma is this: I have a simple static page that does not require JavaScript. Using vue-cli 3, I am attempting to pass the HTML file through webpack for minification purposes. Unfortunately, it seems that accomplishing this task is not as straightforwa ...

What are the recommended guidelines for organizing files in an NPM package for front-end development?

I am creating an NPM package for the front-end and I'm trying to figure out the optimal file structure. My package consists of a code.js file as well as a code.min.js file. Should these files be located in the root directory, a dist folder, or a src f ...

Tips for effectively using the question mark as a separator in a webservice URL

In my nodejs / express project, I am attempting to create a webservice where I separate the URL from parameters using '?' and use '&' as parameter separators. When using this method, it works perfectly fine: app.get("/tableref/:event/ ...

Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their ...

Deleting a row from a table when a similar element is found in another location

My webpage features a table list that showcases users linked to an organization: <script type="text/html" id="userListTemplate"> <div id="user_list_box"> <table class="list" style="margin-bottom: 15px;"> {{#Users} ...

Error in jQuery and Canvas Image Crop: The index or size is invalid, exceeding the permissible limit

Recently, I downloaded and installed the Canvas Image Crop plugin from CodeCanyon but encountered a problem specifically on firefox. An error message kept popping up whenever I tried to upload certain images: "Index or size is negative or greater than the ...

Utilizing jQuery's Ajax functionality to extract filtered data from mySQL

I've been working on sending query strings fetched by clicking radio buttons to the server in order to receive a response in XML format. Although I'm close to finding a solution, I'm struggling to debug why it's not functioning as expec ...

Different ways to display an HTML page in a well by utilizing a div tag and jQuery from a side menu

Check out my Tutorial Page! Currently, I am working on a simple tutorial page utilizing bootstrap 3. My goal is to showcase the HTML file content within the well container on the right side of the page. However, I am facing challenges as I do not want to ...

I am unable to append a new attribute to an object

I am currently working on a project using Node, Express, and Mongoose. In my controller, I'm trying to retrieve all orders for the logged-in client from the database. I want to display the status of each order and based on the state, add the available ...

What is the best way to declare a global TypeScript variable in a definition file to make it accessible for import?

My issue revolves around an external JS library that contains a global parameter: function Thing() { ... } ... var thing = new Thing(); I have a TypeScript definition file named thing.d.ts with the following content: declare var thing: ThingStatic; ex ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

Discovering the method for retrieving post parameters in Node.js

I am currently utilizing Node.js with Express and the httpAsyncClient library in Android. I have sent a request to Express using Post, including parameters. The request goes through successfully, but I am unable to retrieve the parameter in Post. I have ...

Error: Attempting to access a property 'notesObjectInService' that is undefined on the object

I'm currently facing an issue where my controller is unable to load an object from a service called notesFactory. The console.log(typeof notesFactory) statement returns 'undefined', causing notesObjectInService to trigger an exception. Desp ...

Extracting information from Python Bottle with the help of AJAX jQuery

I'm currently working on an HTML page that communicates with a Python script returning a JSON string through AJAX/jQuery. I've set up Bottle for basic URL routing functionality. The issue I'm facing is that my browser indicates that the AJA ...

Issue encountered when attempting to deploy a node/express API with now.sh

Currently, I am in the process of deploying a node/express API with multiple endpoints on now.sh. I am seeking guidance on properly configuring the now.json file for this deployment. In order to provide a visual representation of my project's comple ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here' ...