Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Angular Forms & it's type

 Forms are used to collect, validate, and submit user input in Angular applications.

Angular provides two approaches to handle forms:

  1. Template-Driven Forms

  2. Reactive Forms

Template-Driven vs Reactive Forms

FeatureT emplate-Driven Forms              Reactive Forms
Form logic In HTML template                     In TypeScript
Data bindingTwo-way (ngModel)                  Explicit (FormControl)
ValidationTemplate-based                            Code-based
ScalabilitySmall forms                                 Large/complex forms
TestingHarder                                               Easier
Flexibility                                                       LessMore


🟢 Template-Driven Forms

✅ Characteristics

  • Logic written mostly in HTML

  • Uses [(ngModel)]

  • Easy to learn

  • Best for simple forms

📌 Required Module

import { FormsModule } from '@angular/forms';

📄 Example

HTML

<form #myForm="ngForm"> <input name="email" ngModel required email /> <button [disabled]="myForm.invalid">Submit</button> </form>

✔ Validation required minlength maxlength email pattern

How to intreact with Radio button, Checkbox, Listbox and Dropdownlist with example:

import { FormsModule } from '@angular/forms';
import { Component } from '@angular/core'; @Component({ selector: 'app-student', templateUrl: './student.component.html' }) export class StudentComponent { // Model object (optional but recommended) student = { name: '', gender: '', isActive: false, course: '', skills: [] as string[] }; /* onSubmit(form: any) { console.log('Form Value:', form.value); console.log('Student Object:', this.student); }*/

result: string = ''; onSubmit(form: any) { this.result = `Name: ${this.student.name}, ` + `Gender: ${this.student.gender}, ` + `Active: ${this.student.isActive ? 'Yes' : 'No'}, ` + `Course: ${this.student.course}, ` + `Skills: ${this.student.skills.join(', ')}`; } }


Student.Component.html

<h2>Student Registration Form</h2> <form #studentForm="ngForm" (ngSubmit)="onSubmit(studentForm)"> <!-- TEXTBOX --> <label>Name:</label><br /> <input type="text" name="name" [(ngModel)]="student.name" required /> <br /><br /> <!-- RADIO BUTTON --> <label>Gender:</label><br /> <input type="radio" name="gender" value="Male" [(ngModel)]="student.gender" /> Male <input type="radio" name="gender" value="Female" [(ngModel)]="student.gender" /> Female <br /><br /> <!-- CHECKBOX --> <label> <input type="checkbox" name="isActive" [(ngModel)]="student.isActive" /> Active Student </label> <br /><br /> <!-- DROPDOWN LIST --> <label>Course:</label><br /> <select name="course" [(ngModel)]="student.course" required > <option value="">-- Select Course --</option> <option value="Angular">Angular</option> <option value="React">React</option> <option value="Java">Java</option> </select> <br /><br /> <!-- LISTBOX (MULTI SELECT) --> <label>Skills:</label><br /> <select name="skills" [(ngModel)]="student.skills" multiple size="4" > <option value="HTML">HTML</option> <option value="CSS">CSS</option> <option value="JavaScript">JavaScript</option> <option value="Angular">Angular</option> </select> <br /><br /> <button type="submit" [disabled]="studentForm.invalid"> Submit </button> </form> <hr /> <h3>Form Output</h3> <pre>{{ student | json }}</pre>


Reactive Forms ✅ Characteristics Form logic written in TypeScript Uses FormGroup, FormControl Highly scalable & testable Best for enterprise applications 📌 Required Module import { ReactiveFormsModule } from '@angular/forms'

Component (TS)

form = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), });


in .html file

<form [formGroup]="form"> <input formControlName="email" /> <button [disabled]="form.invalid">Submit</button> </form>


✔ Advantages Strong validation control Dynamic forms Better error handling Clean separation of logic

Create Normal Addition Program in Angular Framework:

import { ReactiveFormsModule } from '@angular/forms';
import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-addition', templateUrl: './addition.component.html' }) export class AdditionComponent { addForm = new FormGroup({ num1: new FormControl('', Validators.required), num2: new FormControl('', Validators.required) }); result: number = 0; calculate() { const n1 = Number(this.addForm.value.num1); const n2 = Number(this.addForm.value.num2); this.result = n1 + n2; } }

Html File

<form [formGroup]="addForm" (ngSubmit)="calculate()"> <label>Number 1:</label> <input type="number" formControlName="num1" /> <br /><br /> <label>Number 2:</label> <input type="number" formControlName="num2" /> <br /><br /> <button type="submit" [disabled]="addForm.invalid"> Add </button> </form> <h3>Result: {{ result }}</h3>

➕ Addition Program (Reactive Form) with Validation
import { ReactiveFormsModule } from '@angular/forms';

import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-addition', templateUrl: './addition.component.html' }) export class AdditionComponent { addForm = new FormGroup({ num1: new FormControl('', [ Validators.required, Validators.pattern('^[0-9]+$') ]), num2: new FormControl('', [ Validators.required, Validators.pattern('^[0-9]+$') ]) }); result: number | null = null; calculate() { if (this.addForm.invalid) { this.addForm.markAllAsTouched(); return; } const n1 = Number(this.addForm.value.num1); const n2 = Number(this.addForm.value.num2); this.result = n1 + n2; } }

<form [formGroup]="addForm" (ngSubmit)="calculate()"> <!-- NUMBER 1 --> <label>Number 1:</label> <input type="text" formControlName="num1" /> <div *ngIf="addForm.get('num1')?.touched && addForm.get('num1')?.errors"> <small *ngIf="addForm.get('num1')?.errors?.['required']"> Number 1 is required </small> <small *ngIf="addForm.get('num1')?.errors?.['pattern']"> Only numbers allowed </small> </div> <br /> <!-- NUMBER 2 --> <label>Number 2:</label> <input type="text" formControlName="num2" /> <div *ngIf="addForm.get('num2')?.touched && addForm.get('num2')?.errors"> <small *ngIf="addForm.get('num2')?.errors?.['required']"> Number 2 is required </small> <small *ngIf="addForm.get('num2')?.errors?.['pattern']"> Only numbers allowed </small> </div> <br /> <button type="submit" [disabled]="addForm.invalid"> Add </button> </form> <h3 *ngIf="result !== null">Result: {{ result }}</h3>


How to use other form elements:

import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { form = new FormGroup({ gender: new FormControl('', Validators.required), hobbies: new FormGroup({ reading: new FormControl(false), sports: new FormControl(false), music: new FormControl(false) }), country: new FormControl('', Validators.required), skills: new FormControl([], Validators.required) }); submittedData: any = null; onSubmit() { if (this.form.invalid) { alert("Please fill all required fields"); return; } const formValue = this.form.value; // Convert checkbox object to array const selectedHobbies = Object.keys(formValue.hobbies!) .filter(key => formValue.hobbies![key]); this.submittedData = { gender: formValue.gender, hobbies: selectedHobbies, country: formValue.country, skills: formValue.skills }; } }
.html file:

<h2>Reactive Form Example</h2> <form [formGroup]="form" (ngSubmit)="onSubmit()"> <!-- Radio Button --> <div> <label><b>Gender:</b></label><br> <input type="radio" formControlName="gender" value="Male"> Male <input type="radio" formControlName="gender" value="Female"> Female <div *ngIf="form.get('gender')?.touched && form.get('gender')?.invalid"> <small style="color:red;">Gender is required</small> </div> </div> <br> <!-- Checkbox --> <div formGroupName="hobbies"> <label><b>Hobbies:</b></label><br> <input type="checkbox" formControlName="reading"> Reading <input type="checkbox" formControlName="sports"> Sports <input type="checkbox" formControlName="music"> Music </div> <br> <!-- Dropdown --> <div> <label><b>Country:</b></label><br> <select formControlName="country"> <option value="">Select Country</option> <option value="India">India</option> <option value="USA">USA</option> <option value="UK">UK</option> </select> <div *ngIf="form.get('country')?.touched && form.get('country')?.invalid"> <small style="color:red;">Country is required</small> </div> </div> <br> <!-- Listbox (Multi Select) --> <div> <label><b>Skills:</b></label><br> <select formControlName="skills" multiple size="4"> <option value="Java">Java</option> <option value="Angular">Angular</option> <option value="Spring Boot">Spring Boot</option> <option value="SQL">SQL</option> </select> <div *ngIf="form.get('skills')?.touched && form.get('skills')?.invalid"> <small style="color:red;">Select at least one skill</small> </div> </div> <br> <button type="submit">Submit</button> </form> <hr> <!-- Display Submitted Data --> <div *ngIf="submittedData"> <h3>Submitted Data</h3> <p><b>Gender:</b> {{ submittedData.gender }}</p> <p><b>Hobbies:</b> {{ submittedData.hobbies.join(', ') }}</p> <p><b>Country:</b> {{ submittedData.country }}</p> <p><b>Skills:</b> {{ submittedData.skills.join(', ') }}</p> </div>



Post a Comment

1 Comments

  1. import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';

    @Component({
    selector: 'app-math-operations',
    standalone: true,
    imports: [FormsModule],
    templateUrl: './math-operations.component.html',
    styleUrl: './math-operations.component.css'
    })
    export class MathOperationsComponent {
    num1: number = 0;
    num2: number = 0
    result: number = 0;


    addOperation(){
    this.result = Number(this.num1) + Number(this.num2);
    }
    subOperation(){
    this.result = Number(this.num1) - Number(this.num2);
    }

    mulOperation(){
    this.result = Number(this.num1) * Number(this.num2);
    }

    divOperation(){
    this.result = Number(this.num1) / Number(this.num2);
    }
    }
    Calculator program ts file

    ReplyDelete

POST Answer of Questions and ASK to Doubt