Angular-Formly : Adding Form fields dynamically on user click

Masood Alam picture Masood Alam · Sep 9, 2015 · Viewed 24.7k times · Source

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

Answer

user3769694 picture user3769694 · Feb 20, 2016

See this Plunker

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);
  };
});