Angular — Template Forms
Template-Driven Forms
import { FormsModule } from '@angular/forms';
@Component({
imports: [FormsModule],
template: `
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
<input name="email" ngModel required email>
<input name="password" ngModel required minlength="6">
<button [disabled]="loginForm.invalid">Login</button>
</form>
`
})
export class LoginComponent {
onSubmit(form: any) {
console.log(form.value);
}
}
Reactive Forms
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
@Component({
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="email">
<input formControlName="password">
<button [disabled]="form.invalid">Login</button>
</form>
`
})
export class LoginComponent {
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(6)])
});
onSubmit() {
console.log(this.form.value);
}
}
Form Validation
// Template-driven
// In template: *ngIf="email.invalid && email.touched"
// Reactive
this.form.get('email')?.invalid
Mini Practice
- Create a template-driven form
- Create a reactive form
- Add validation
- Handle form submission
Up Next
Continue with Form Validation — validating form inputs.
Related Topics
Frequently Asked Questions about Template Forms
What is Template Forms in Angular?
Template Forms is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Template Forms?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Template Forms.
Why is Template Forms important in Angular?
Template Forms is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.