DeployU
Interviews / Frontend Engineering / What is the difference between a template-driven and a reactive form in Angular?

What is the difference between a template-driven and a reactive form in Angular?

conceptual Forms Interactive Quiz Code Examples

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?

Wrong Approach

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.

Right Approach

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

FeatureTemplate-Driven FormReactive Form
SetupMinimal setup required.More setup required.
LogicThe logic is in the template.The logic is in the component class.
TestingMore difficult to test.Easier to test.
FlexibilityLess flexible.More flexible.
Use CasesSimple 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?