Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 74 ยท Projects

Project: Quiz App with Reactive Forms

Build a quiz app in Angular with questions loaded from data, a reactive form for the answers, a scored result and a small animation, with runnable logic and UI stand-ins.

A quiz looks simple, but it exercises a pleasant set of Angular skills: data-driven templates, a form whose controls are created from data, a derived score, and a screen that changes from "answering" to "result". In this project you will plan the data, build the form with reactive forms, calculate the score, and finish with a small animation.

You should know Reactive Forms, Dynamic Forms and Signals: signal, computed and effect first. The quiz content here is our own invented example.

Real versus stand-in. The typescript blocks are the real Angular app, to read and copy into a project made with ng new; the site cannot compile Angular. The runnable examples are stand-ins: one runs the scoring logic in TypeScript, and one is a working quiz UI in plain JavaScript that follows the same design.

Step 1: the plan

  • A question has an id, a text, a list of options and the index of the correct option.
  • The form has one control per question, created from the data. A control holds the chosen option index, or null while unanswered.
  • The score and the "unanswered" count are derived: never stored by hand.
  • The screen has two states: answering and result. A signal holds which one is active.
flowchart LR
  D["QUESTIONS (data)"] --> F["FormGroup<br/>one control per question"]
  F --> S["score()<br/>computed from form value"]
  F --> U["Template<br/>@for questions, radio options"]
  S --> R["Result view"]

The data builds the form, the form value feeds the score, and the template renders both.

Step 2: the data and the scoring rules

Keep the scoring in a plain function. It does not need Angular, so it is easy to test (Testing Angular Applications).

TypeScript
// quiz.ts
export interface Question {
  id: string;
  text: string;
  options: string[];
  correct: number; // index into options
}

export const QUESTIONS: Question[] = [
  { id: 'q1', text: 'Which function creates a writable signal?', options: ['computed()', 'signal()', 'effect()'], correct: 1 },
  { id: 'q2', text: 'Which block repeats a template for each item?', options: ['@if', '@switch', '@for'], correct: 2 },
  { id: 'q3', text: 'What does a FormControl hold?', options: ['One value and its status', 'A whole page', 'A route'], correct: 0 },
];

export type Answers = Record<string, number | null>;

export function scoreQuiz(questions: Question[], answers: Answers): { correct: number; unanswered: number } {
  let correct = 0;
  let unanswered = 0;
  for (const q of questions) {
    const given = answers[q.id];
    if (given === null || given === undefined) unanswered++;
    else if (given === q.correct) correct++;
  }
  return { correct, unanswered };
}

Step 3: the component

The form is built with FormBuilder: a loop turns every question into a control. Because the quiz is data, adding a question never touches the template.

TypeScript
// quiz-page.ts
import { Component, computed, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { toSignal } from '@angular/core/rxjs-interop';
import { Answers, QUESTIONS, scoreQuiz } from './quiz';

@Component({
  selector: 'app-quiz-page',
  imports: [ReactiveFormsModule],
  template: `
    @if (!finished()) {
      <form [formGroup]="form" (ngSubmit)="finish()">
        @for (q of questions; track q.id) {
          <fieldset>
            <legend>{{ q.text }}</legend>
            @for (option of q.options; track $index) {
              <label>
                <input type="radio" [formControlName]="q.id" [value]="$index" />
                {{ option }}
              </label>
            }
          </fieldset>
        }
        <p>{{ answered() }} of {{ questions.length }} answered</p>
        <button type="submit">Finish</button>
      </form>
    } @else {
      <section class="result" aria-live="polite">
        <h2>You scored {{ result().correct }} / {{ questions.length }}</h2>
        @if (result().unanswered > 0) {
          <p>{{ result().unanswered }} unanswered.</p>
        }
        <button type="button" (click)="restart()">Try again</button>
      </section>
    }
  `,
  styles: `
    .result { animation: pop 300ms ease-out; }
    @keyframes pop { from { opacity: 0; transform: scale(0.95); } }
  `,
})
export class QuizPage {
  private readonly fb = inject(FormBuilder);
  protected readonly questions = QUESTIONS;

  protected readonly form = this.fb.group(
    Object.fromEntries(QUESTIONS.map(q => [q.id, this.fb.control<number | null>(null)])),
  );

  private readonly value = toSignal(this.form.valueChanges, { initialValue: this.form.value });
  protected readonly finished = signal(false);

  protected readonly answered = computed(
    () => Object.values(this.value()).filter(v => v !== null && v !== undefined).length,
  );
  protected readonly result = computed(() => scoreQuiz(QUESTIONS, this.value() as Answers));

  protected finish(): void {
    this.finished.set(true);
  }

  protected restart(): void {
    this.form.reset();
    this.finished.set(false);
  }
}

Three details matter. toSignal(form.valueChanges) turns the form's observable into a signal, so answered and result are plain computed() values (Signals and RxJS Interop). The radio inputs share one formControlName per question, so selecting an option replaces the previous one. And the result block has aria-live="polite", so a screen reader announces the score when it appears (Security and Accessibility).

The animation is plain CSS: a keyframe that fades and scales the result in. With Angular's animate.enter feature you could use a class instead, but a CSS animation on a block that is added to the page is enough here.

Step 4: run the scoring logic

The first stand-in runs scoreQuiz with several answer sets, including blanks and an unknown answer.

TypeScript Scoring a quiz

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A blank answer counts as unanswered, not wrong, and a missing key behaves like null. That is why the function checks for both null and undefined.

Step 5: see it as a UI

The second stand-in is the same quiz in plain JavaScript. A state object plays the part of the form value, and a render() function plays the part of the template. Real Angular updates only what changed; this version redraws, which is fine for a demo.

A working quiz UI

Try answering only two questions and pressing Finish: the result reports one unanswered question, just as the real component does.

Ideas to extend it

  • Add a timer with a signal and setInterval, and finish automatically at zero.
  • Shuffle the questions once at start-up and keep the order in a signal.
  • Load the questions with httpResource (linkedSignal, resource and httpResource).
  • Add a Validators-based rule that blocks Finish until every question is answered.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the form built by looping over the question data?

    When the controls are created from data, the data stays the single source of truth for both the form and the template.
  2. 2. What does toSignal(this.form.valueChanges) give you?

    toSignal converts the observable into a signal, so derived values like the score can be plain computed() values.
  3. 3. Why does the scoring function treat null and undefined the same?

    A control starts as null, and an untouched key may be missing from an object, so both must count as unanswered.
  4. 4. What is aria-live="polite" for on the result block?

    A live region tells assistive technology to read changes aloud without moving focus.

Summary

  • Describe the quiz as data, build one form control per question from it, and keep the template generic.
  • Put the scoring in a plain function so it can be tested without Angular.
  • Convert valueChanges with toSignal() and derive answered and result with computed().
  • Switch between answering and result with one signal and @if/@else.
  • Use a live region and labelled fieldsets so the quiz works with a screen reader.

Next: Project: Expense Tracker with Services and localStorage.