Questions
What is the difference between a template-driven and a reactive form in Angular?
The Scenario
You are a frontend engineer at an e-commerce company. You are building a new form that allows users to create a new product.
You are not sure whether to use a template-driven form or a reactive form.
The Challenge
Explain the difference between a template-driven and a reactive form in Angular. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might think that they are interchangeable. They might not be aware of the difference in features or the design implications of choosing one over the other.
A senior engineer would be able to provide a detailed explanation of the differences between a template-driven and a reactive form. They would also be able to explain the trade-offs between each approach and would have a clear recommendation for which one to use in this use case.
Step 1: Understand the Key Differences
| Feature | Template-Driven Form | Reactive Form |
|---|---|---|
| Setup | Minimal setup required. | More setup required. |
| Logic | The logic is in the template. | The logic is in the component class. |
| Testing | More difficult to test. | Easier to test. |
| Flexibility | Less flexible. | More flexible. |
| Use Cases | Simple forms with minimal validation. | Complex forms with custom validation and dynamic fields. |
Step 2: Choose the Right Tool for the Job
For our use case, we should use a reactive form. This is because we are building a complex form with custom validation and dynamic fields.
Step 3: Code Examples
Here are some code examples that show the difference between the two approaches:
Template-Driven Form:
<form #myForm="ngForm">
<input type="text" name="name" ngModel required>
<button [disabled]="!myForm.valid">Submit</button>
</form>Reactive Form:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-form',
template: `
<form [formGroup]="myForm">
<input type="text" formControlName="name">
<button [disabled]="!myForm.valid">Submit</button>
</form>
`
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl('', Validators.required)
});
}
} Practice Question
You are building a simple contact form with only a few fields and no validation. Which of the following would be the most appropriate?