Template-Driven Forms
Template-driven forms are perfect for beginners starting with Angular.
They use simple HTML-based syntax combined with Angular directives, making it easy to create and manage forms without heavy TypeScript code.
Example: Build a basic login form
Step 1: Create a new Angular project
Step 2: Generate a new component
Step 3: Build the form in HTML
Open form-component.component.html and add
Step 4: Add form logic in TypeScript
Edit form-component.component.ts
Step 5: Style your form (Optional)
In form-component.component.css
Step 6: Display the form in the app
In app.component.html
Important
Open app.module.ts and make sure you import FormsModule
Step 7: Run the application
Example: Build a basic login form
Step 1: Create a new Angular project
ng new angular-forms
Step 2: Generate a new component
ng g c form-component
Step 3: Build the form in HTML
Open form-component.component.html and add
<div class="container"> <h2>Template-Driven Form</h2> <form #login="ngForm" (ngSubmit)="submit(login)"> <div class="form-group"> <label for="fname">First Name:</label><br /> <input type="text" name="fname" class="form-control" [(ngModel)]="user.fname"> </div> <pre></pre> <div class="form-group"> <label for="lname">Last Name:</label><br /> <input type="text" name="lname" class="form-control" [(ngModel)]="user.lname"> </div> <pre></pre> <div class="form-group"> <label for="email">Email:</label><br /> <input type="email" name="email" class="form-control" [(ngModel)]="user.email"> </div> <pre></pre> <div class="form-group"> <label for="password">Password:</label><br /> <input type="password" name="password" class="form-control" [(ngModel)]="user.password"> </div> <pre></pre> <button class="btn btn-primary" type="submit">Submit</button> </form></div>
Step 4: Add form logic in TypeScript
Edit form-component.component.ts
import { Component } from '@angular/core';
@Component({ selector: 'app-form-component', templateUrl: './form-component.component.html', styleUrls: ['./form-component.component.css']})export class FormComponentComponent { user = { fname: '', lname: '', email: '', password: '' }
submit(login) { console.log("Form submitted!", this.user); }}
Step 5: Style your form (Optional)
In form-component.component.css
div { text-align: center;}
label { text-align: left;}
Step 6: Display the form in the app
In app.component.html
<app-form-component></app-form-component>
Important
Open app.module.ts and make sure you import FormsModule
import { FormsModule } from '@angular/forms';
@NgModule({ imports: [ BrowserModule, FormsModule ], // other code...})export class AppModule { }
Step 7: Run the application
ng serve
Visit http://localhost:4200 - you will see your form in action