How to Implement Angular Forms?
Last Updated :
21 May, 2024
Creating a Form in Angular includes the use of directives such as ngSubmit and ngModel. We will be using a functional component to render the elements. Various HTML elements are created in the project. To implement the project we will create the styling using CSS.
Prerequisites:
Approach
- Run ng new my-angular-form-project command to set up the react project.
- HTML From to create the form structure
- HTML Input of type text, textarea, number, radio, checkbox and add respective labels for the inputs.
- HTML Button for reset and submit actions.
- CSS class and properties to style the Form label, inputs and buttons.
Project Structure:
Folder structureSteps to Create Angular Project
Step 1: Run the following command to install Angular CLI globally.
npm install -g @angular/[email protected]
Step 2: Go to Form directory and run this command to create angular project.
ng new my_angular_form_project
The Updated Dependenices in the package.json file:
"dependencies":
{
"@angular/animations": "^16.0.0",
"@angular/common": "^16.0.0",
"@angular/compiler": "^16.0.0",
"@angular/core": "^16.0.0",
"@angular/forms": "^16.0.0",
"@angular/platform-browser": "^16.0.0",
"@angular/platform-browser-dynamic": "^16.0.0",
"@angular/router": "^16.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
}
Step 3: Make changes to the project file according to give code example.
Example: To demonstrate creating an angular form.
HTML
<!-- /app/app.component.html -->
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Form Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="FormController">
<div class="App">
<h1>Form in AngularJS</h1>
<fieldset>
<form (ngSubmit)="handleSubmit()">
<label for="firstname">First Name*</label>
<input
type="text"
name="firstname"
[(ngModel)]="formData.firstName"
placeholder="Enter First Name"
required
/>
<label for="lastname">Last Name*</label>
<input
type="text"
name="lastname"
[(ngModel)]="formData.lastName"
placeholder="Enter Last Name"
required
/>
<label for="email">Enter Email*</label>
<input
type="email"
name="email"
[(ngModel)]="formData.email"
placeholder="Enter email"
required
/>
<label for="contact">Contact*</label>
<input
type="tel"
name="contact"
[(ngModel)]="formData.contact"
placeholder="Enter Mobile number"
required
/>
<label for="gender">Gender*</label>
<input
type="radio"
name="gender"
value="male"
[(ngModel)]="formData.gender"
/>
Male
<input
type="radio"
name="gender"
value="female"
[(ngModel)]="formData.gender"
/>
Female
<input
type="radio"
name="gender"
value="other"
[(ngModel)]="formData.gender"
/>
Other
<label>Your best Subject</label>
<input
type="checkbox"
name="english"
[(ngModel)]="formData.subjects.english"
/>
English
<input
type="checkbox"
name="maths"
[(ngModel)]="formData.subjects.maths"
/>
Maths
<input
type="checkbox"
name="physics"
[(ngModel)]="formData.subjects.physics"
/>
Physics
<label for="url">Enter URL*</label>
<input
type="url"
name="url"
[(ngModel)]="formData.url"
placeholder="Enter url"
required
/>
<label for="about">About</label>
<textarea
name="about"
[(ngModel)]="formData.about"
placeholder="About yourself"
required
></textarea>
<button type="reset" (click)="resetForm()">Reset</button>
<button type="submit">Submit</button>
</form>
</fieldset>
</div>
</body>
</html>
HTML
<!--index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyAngularFormProject</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
CSS
/* //app/app.component.css */
body {
background: #f3f3f3;
text-align: center;
}
.App {
background-color: #fff;
border-radius: 15px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
padding: 10px 20px;
transition: transform 0.2s;
width: 500px;
text-align: center;
margin: auto;
margin-top: 20px;
}
h1 {
font-size: x-large;
text-align: center;
color: #327c35;
}
fieldset {
border: none;
}
input {
display: block;
width: 100%;
/* margin-bottom: 15px; */
padding: 8px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 3px;
font-size: 12px;
}
input[type="radio"],
input[type="checkbox"] {
display: inline;
width: 10%;
}
select {
display: block;
width: 100%;
margin-bottom: 15px;
padding: 10px;
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 5px;
}
label {
font-size: 15px;
display: block;
width: 100%;
margin-top: 8px;
margin-bottom: 5px;
text-align: left;
color: #555;
font-weight: bold;
}
button {
padding: 15px;
border-radius: 10px;
margin: 15px;
border: none;
color: white;
cursor: pointer;
background-color: #4caf50;
width: 40%;
font-size: 16px;
}
textarea {
resize: none;
width: 98%;
min-height: 100px;
max-height: 150px;
}
JavaScript
// app/app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, FormsModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'my-angular-form-project';
formData = {
firstName: '',
lastName: '',
email: '',
contact: '',
gender: 'male',
subjects: {
english: true,
maths: false,
physics: false
},
url: '',
about: ''
};
handleSubmit() {
console.log(this.formData);
// Add your form submission logic here
}
resetForm() {
this.formData = {
firstName: '',
lastName: '',
email: '',
contact: '',
gender: 'male',
subjects: {
english: true,
maths: false,
physics: false
},
url: '',
about: ''
};
}
}
JavaScript
//main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent)
.catch((err) => console.error(err));
To run this project:
npm start
Output: This output will be visible on localhost:4200/ on the browser window.
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
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
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
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
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
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