How would I go about adding the capability in the form so that the user can add more input fields by clicking the "Add". This using the angular formly library.
Here is an example of the exact feature but done using only angularjs.
Adding form fields dynamically
In order to add and remove fields, we will describe some steps, which are shown as follows: This is the first step, and in this step, we will Import FormsModule. In this step, we are going to Update TS file. For this, we will use the angular forms library to import the FormArray, FormControl, FormBuilder, and FormGroup.
Knowledge of Angular Reactive form, JavaScript. What is an Angular FormArray? In Angular Reactive Forms, every form has a form model defined programmatically using the FormControl and FormGroup APIs, or alternatively using the more concise FormBuilder API, which we will be using throughout this guide.
In this file we will first import FormGroup, FormControl,FormArray and FormBuilder from angular forms library. In this step, we will write code of html form with ngModel. so add following code to app.component.html file. I used bootstrap class on this form. if you want to add than then follow this link too: Install Boorstrap 4 to Angular 9.
The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl , FormGroup, or FormArray. It reduces the amount of boilerplate needed to build complex forms. Angular1 3 came and if you are new then you must check below link: 1.
Here is an example of what you need. As you can see in the plunker, there is a TextArea
which can be created dynamically on button click. The created TextAreas
can also be removed with the remove
button click.
See the HTML below
<div class="col-sm-10"> <input type="button" class="btn btn-info" ng-click="addNewChoice()" value="ADD QUESTION"> <div class="col-sm-4"> <fieldset data-ng-repeat="field in choiceSet.choices track by $index"> <textarea rows="4" cols="50" ng-model=" choiceSet.choices[$index]"></textarea> <button type="button" class="btn btn-default btn-sm" ng-click="removeChoice($index)"> <span class="glyphicon glyphicon-minus"></span> REMOVE </button> </fieldset> </div> </div>
and the JS will be as below
var app = angular.module('myApp', []); app.controller('inspectionController', function($scope, $http) { $scope.choiceSet = { choices: [] }; $scope.quest = {}; $scope.choiceSet.choices = []; $scope.addNewChoice = function() { $scope.choiceSet.choices.push(''); }; $scope.removeChoice = function(z) { $scope.choiceSet.choices.splice(z, 1); }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With