How to create the dynamic forms in AngularJS ?
Last Updated :
25 Jul, 2024
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.
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=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js">
</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:
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=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<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:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read