When you're building an Angular app, you'll eventually need to use forms — for login, registration, feedback, or something else. In Angular, there are two main types of forms:
- Template-driven forms
- Reactive forms
Let’s go over each one in simple terms and look at some examples.
🧾 1. Template-driven Forms
These forms are written mostly in the HTML template. Angular takes care of a lot behind the scenes. They’re great for simple use cases.
🔧 Setup
First, make sure to import FormsModule
in your app.module.ts
:
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [FormsModule],
})
export class AppModule {}
🧪 Example
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<input name="username" ngModel required />
<button type="submit">Submit</button>
</form>
onSubmit() {
console.log('Form submitted!');
}
Angular automatically tracks the form and its validity. You just need to use ngModel
and give your form a reference.
🧠 2. Reactive Forms
Reactive forms are built in the component TypeScript file using form classes. This approach gives you more control, and it’s great for larger or more complex forms.
🔧 Setup
Make sure to import ReactiveFormsModule
in your app.module.ts
:
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ReactiveFormsModule],
})
export class AppModule {}
🧪 Example
import { FormGroup, FormControl } from '@angular/forms';
form = new FormGroup({
username: new FormControl(''),
});
onSubmit() {
console.log(this.form.value);
}
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="username" />
<button type="submit">Submit</button>
</form>
This method is more structured. You define the form in the component, then bind it in the template.
🆚 Which One Should You Use?
Here’s a quick comparison:
Use this… | When… |
---|---|
Template-driven | For simple forms and quick setup |
Reactive | For complex forms, custom logic |
Both are useful. Pick the one that fits your project best.
✅ Conclusion
Angular gives you the flexibility to work with forms in different ways. If you’re new to forms in Angular, start with template-driven. Once you’re comfortable, give reactive forms a try—they open up a lot of powerful features.
Let me know in the comments if you'd like a follow-up on validation or dynamic form fields!
Happy coding! 🚀
Top comments (0)