Open In App

How to create the dynamic forms in AngularJS ?

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In AngularJS, we need to create dynamic forms to make the user interact. We can create and apply different behaviors to the forms to represent and accept the data from the user. We can create dynamic forms using ng-repeat and ng-show in AngularJS. In this article, we will see how we can create dynamic forms in AngularJS.

Steps to create dynamic forms in AngularJS

The below steps will be followed for creating dynamic forms in AngularJS Applications.

Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir dynamic-form
cd dynamic-form

Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file.

We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.

Dynamic Form Fields using ng-repeat Directive

In this approach, we create the dynamic and attractive form using the ng-repeat directive in AngularJS. Here we have used the array of objects that will store the information about the users. Each user can add his information along with the Gender and Interest from the radio and check buttons. Here, the ng-repeat directive dynamically generates the input fields, radio buttons, and checkboxes for each item in the array. This approach and easily be used for the dynamic creation and manipulation of the form fields.

Example: Below is an example that demonstrates the creation of dynamic forms in AngularJS using ng-repeat Directive.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
  
        .container {
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 10px;
            max-width: 400px;
            width: 100%;
        }
  
        h1 {
            color: green;
        }
  
        h3 {
            font-weight: bold;
            margin-top: 10px;
        }
  
        form {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
  
        .add-button,
        .remove-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px;
            cursor: pointer;
            border-radius: 5px;
            text-align: center;
            transition: background-color 0.3s;
        }
  
        .remove-button {
            background-color: #FF0000;
        }
  
        .add-button:hover {
            background-color: #45a049;
        }
  
        .remove-button:hover {
            background-color: #CC0000;
        }
  
        .form-element {
            display: flex;
            flex-direction: column;
        }
  
        .form-label {
            margin-bottom: 5px;
        }
  
        .error-message {
            color: red;
        }
  
        @media screen and (max-width: 600px) {
            .container {
                padding: 10px;
            }
  
            form {
                gap: 5px;
            }
  
            .form-element {
                gap: 5px;
            }
        }
  
        .user-details-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
  
        .user-details {
            flex: 1;
            background-color: #f0f0f0;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: flex;
            flex-direction: column;
        }
  
        .user-details h4 {
            font-weight: bold;
        }
  
        .user-details p {
            margin: 5px 0;
        }
  
        .form-element input[type="text"] {
            margin: 5px 0;
        }
  
        .form-element input[type="checkbox"] {
            margin: 0 5px;
        }
  
        .radio-container {
            display: flex;
            gap: 20px;
            margin: 5px 0;
        }
  
        .radio-container label {
            margin-right: 5px;
        }
    </style>
</head>
  
<body ng-app="DynamicFormsApp" 
      ng-controller="FormController">
    <div class="container">
        <h1 style="color: #4CAF50;">
              GeeksforGeeks
          </h1>
        <h3>
              Approach 1: Dynamic Form Fields Using ng-repeat
          </h3>
        <form name="dynamicForm">
            <div ng-repeat="name in names track by $index" 
                 class="form-element" 
                 ng-show="$index === names.length - 1">
                <input type="text" 
                       ng-model="name.name"
                       name="name{{$index}}" 
                       placeholder="Name {{$index + 1}}">
                <div class="form-element">
                    <label class="form-label">
                          Select a Gender for {{name.name}}:
                      </label>
                    <label>
                        <input type="radio"
                               ng-model="name.gender" 
                               value="male"
                               id="male{{$index}"> Male
                    </label>
                    <label>
                        <input type="radio"
                               ng-model="name.gender"
                               value="female"
                               id="female{{$index}"> Female
                    </label>
                </div>
                <div class="form-element">
                    <label class="form-label">
                          Select Interests for {{name.name}}:
                      </label>
                    <label>
                        <input type="checkbox"
                               ng-model="name.interests.sports"
                               id="sports{{$index}"> Sports
                    </label>
                    <label>
                        <input type="checkbox" 
                               ng-model="name.interests.movies"
                               id="movies{{$index}"> Movies
                    </label>
                    <label>
                        <input type="checkbox" 
                               ng-model="name.interests.travel"
                               id="travel{{$index}"> Travel
                    </label>
                </div>
                <button ng-click="removeName($index)"
                        class="remove-button">
                      Remove
                  </button>
            </div>
            <button ng-click="addName()"
                    class="add-button">
                  Add Name
              </button>
            <p class="error-message"
               ng-show="dynamicForm.$invalid">
               Please fill out all required fields.
            </p>
        </form>
        <div class="user-details-container">
            <div ng-repeat="name in names track by $index" 
                 class="user-details" 
                 ng-show="name.name">
                <h4>User {{$index + 1}}</h4>
                <p>
                      <strong>Name:</strong> {{name.name}}
                  </p>
                <p>
                      <strong>Gender:</strong> {{name.gender}}
                  </p>
                <p>
                      <strong>Interests:</strong>
                  </p>
                <ul>
                    <li ng-show="name.interests.sports">
                          Sports
                      </li>
                    <li ng-show="name.interests.movies">
                          Movies
                      </li>
                    <li ng-show="name.interests.travel">
                          Travel
                      </li>
                </ul>
            </div>
        </div>
    </div>
  
    <script>
        angular.module('DynamicFormsApp', [])
            .controller('FormController', function ($scope) {
                $scope.names = [{
                    name: '', gender: '',
                    interests: { sports: false, 
                                 movies: false, 
                                 travel: false }
                }];
  
                $scope.addName = function () {
                    $scope.names.push({
                        name: '', gender: '',
                        interests: { sports: false,
                                     movies: false, 
                                     travel: false }
                    });
                };
                $scope.removeName = function (index) {
                    $scope.names.splice(index, 1);
                };
            });
    </script>
</body>
  
</html>


Output:

e1

Dynamic Form Fields using ng-show Directive

In this approach, we are using the ng-show directive to create the dynamic forms by selectively displaying the form steps which are based on the value of the currentStep variable. Here we have embedded each step in the div element container which is in the class of “form-step”. Using this approach, we create step-by-step dynamic forms that allow the users to enter the data for each step before going to the next step.

Example: Below is an example that demonstrates the creation of dynamic forms in AngularJS using ng-show Directive.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <link rel="stylesheet" href=
    <style>
        body {
            background-color: #f0f8ff;
        }
  
        .form-container {
            width: 600px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #007BFF;
            background-color: #fff;
            font-family: Arial, sans-serif;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
  
        h1 {
            color: #008000;
        }
  
        .form-step {
            border: 1px solid #007BFF;
            margin-bottom: 20px;
            background-color: #f0f8ff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            display: none;
        }
  
        .active-step {
            display: block;
        }
  
        .form-button {
            background-color: #007BFF;
            color: #fff;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
  
        .form-button:hover {
            background-color: #0056b3;
        }
  
        .form-button[disabled] {
            background-color: #0056b3;
            cursor: not-allowed;
        }
  
        .back-button,
        .forward-button {
            background-color: #0056b3;
            color: #fff;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            font-size: 16px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
  
        .back-button:hover,
        .forward-button:hover {
            background-color: #0056b3;
        }
  
        table {
            width: 100%;
            border: 1px solid #ddd;
            border-collapse: collapse;
        }
  
        th,
        td {
            padding: 10px;
            text-align: left;
            border: 1px solid #ddd;
        }
    </style>
</head>
  
<body ng-app="dynamicFormApp"
      ng-controller="DynamicFormController">
    <div class="form-container">
        <h1>GeeksforGeeks</h1>
        <h3>
              Approach 2: Dynamic Form Fields Using ng-show
          </h3>
        <form name="dynamicForm" ng-submit="submitForm()">
            <div class="form-step"
                 ng-class="{ 'active-step': currentStep === 1 }">
                <h3>Step 1: Personal Information</h3>
                <div>
                    <label for="firstName">First Name:</label>
                    <input type="text" 
                           id="firstName"
                           name="firstName"
                           ng-model="formData.firstName" required>
                </div>
                <div>
                    <label for="lastName">Last Name:</label>
                    <input type="text" 
                           id="lastName" 
                           name="lastName" 
                           ng-model="formData.lastName" required>
                </div>
                <button class="form-button" 
                        ng-click="nextStep(2)">Next
                  </button>
            </div>
  
            <div class="form-step" 
                 ng-class="{ 'active-step': currentStep === 2 }">
                <h3>Step 2: Contact Information</h3>
                <div>
                    <label for="email">Email:</label>
                    <input type="email" 
                           id="email"
                           name="email" 
                           ng-model="formData.email" required>
                </div>
                <div>
                    <label for="phone">Phone:</label>
                    <input type="tel" 
                           id="phone"
                           name="phone"
                           ng-model="formData.phone" required>
                </div>
                <button class="form-button back-button" 
                        ng-click="prevStep(1)">Back
                  </button>
                <button class="form-button forward-button"
                        ng-click="nextStep(3)">Next
                  </button>
            </div>
  
            <div class="form-step" 
                 ng-class="{ 'active-step': currentStep === 3 }">
                <h3>Step 3: Additional Information</h3>
                <div>
                    <label for="address">Address:</label>
                    <input type="text" 
                           id="address"
                           name="address" 
                           ng-model="formData.address" required>
                </div>
                <button class="form-button back-button" 
                        ng-click="prevStep(2)">Back
                  </button>
                <button class="form-button" 
                        ng-click="submitForm()" 
                        ng-disabled="currentStep !== 3">Submit
                  </button>
            </div>
        </form>
        <div ng-show="showSubmitted">
            <h3>Form Submitted!</h3>
            <table>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Address</th>
                </tr>
                <tr ng-repeat="user in userData">
                    <td>{{ user.firstName }}</td>
                    <td>{{ user.lastName }}</td>
                    <td>{{ user.email }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.address }}</td>
                </tr>
            </table>
        </div>
    </div>
    
    <script>
        angular.module('dynamicFormApp', [])
            .controller('DynamicFormController', function ($scope) {
                $scope.currentStep = 1;
                $scope.showSubmitted = false;
                $scope.formData = {};
                $scope.userData = [];
                $scope.nextStep = function (step) {
                    $scope.currentStep = step;
                };
                $scope.prevStep = function (step) {
                    $scope.currentStep = step;
                };
                $scope.submitForm = function () {
                    $scope.userData.push(angular.copy($scope.formData));
                    $scope.formData = {};
                    $scope.currentStep = 1;
                    $scope.showSubmitted = true;
                };
            });
    </script>
</body>
  
</html>


Output:

e2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads