Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 74 ยท Practice and Review

Practice Exercises with Solutions

Twenty graded Angular exercises on signals, templates, dependency injection, routing, forms and RxJS, each with a full solution and runnable stand-ins for the logic.

Reading about Angular teaches you to recognize it. Writing it teaches you to use it. This page gives you 20 exercises, graded from easy to hard, covering the topics of the whole tutorial: signals, templates, dependency injection, routing, forms and RxJS. Every exercise has a task, and every task has a complete solution further down in the same section.

The best way to use them: read the task, write your own answer on paper or in a scratch project, and only then read the solution. If you got stuck, go back to the lesson linked in the section heading. Do not worry if your answer looks different; there is usually more than one good one. Compare ideas, not letters.

Real versus stand-in. The typescript and html solutions are real Angular code and read-only, because this site cannot run the Angular compiler. Three runnable examples re-create the logic of many solutions as plain TypeScript with tiny stand-ins (a signal, a dependency-injection container, a route matcher, validators and an Observable). They are simplified models, not Angular itself, and everything they print is deterministic. For real practice, create a project with ng new (Setup and the Angular CLI).

flowchart LR
  A["Read the task"] --> B["Write your own answer"]
  B --> C["Compare with the solution"]
  C --> D["Run the stand-in<br/>and change it"]
  D --> A

The practice loop: attempt first, compare second, experiment third.

Levels: Easy = one concept, Medium = two concepts together, Hard = needs a design decision.

Part 1: Signals (exercises 1 to 5)

Review: Signals: signal, computed and effect, Signals in Components and linkedSignal, resource and httpResource.

Exercise 1 (Easy): a counter with a step

Build a counter component. It has a count signal starting at 0, a step signal starting at 1 and a button that adds the step to the count. Show the count and its double; the double must never be stored in its own variable that you update by hand.

Solution

TypeScript
@Component({
  selector: 'app-counter',
  template: `
    <p>{{ count() }} (double: {{ double() }})</p>
    <input type="number" [value]="step()" (input)="step.set(+$any($event.target).value)" />
    <button (click)="increment()">Add step</button>
  `,
})
export class Counter {
  readonly count = signal(0);
  readonly step = signal(1);
  readonly double = computed(() => this.count() * 2);

  increment(): void {
    this.count.update(current => current + this.step());
  }
}

update receives the current value, which is safer than reading and writing in two steps. double is derived with computed, so it is always correct.

Exercise 2 (Easy): fix the stale name

A learner wrote fullName = this.first() + ' ' + this.last(); as a class field. Changing last never changes the greeting. Why, and how do you fix it?

Solution: The field expression runs once, when the object is created, and stores a plain string. Wrap it in computed:

TypeScript
readonly first = signal('Ada');
readonly last = signal('Lovelace');
readonly fullName = computed(() => `${this.first()} ${this.last()}`);

Now fullName() recomputes when either signal changes, and only then.

Exercise 3 (Medium): todo statistics

Hold a list of todos (id, title, done) in a signal. Provide toggle(id) and two derived values: the number of remaining todos and the percentage done (0 when the list is empty). Do not mutate the objects in place.

Solution

TypeScript
readonly todos = signal<readonly Todo[]>([
  { id: 1, title: 'Learn signals', done: true },
  { id: 2, title: 'Learn routing', done: false },
]);

readonly remaining = computed(() => this.todos().filter(t => !t.done).length);

readonly percentDone = computed(() => {
  const total = this.todos().length;
  return total === 0 ? 0 : Math.round((100 * (total - this.remaining())) / total);
});

toggle(id: number): void {
  this.todos.update(list => list.map(t => (t.id === id ? { ...t, done: !t.done } : t)));
}

map and the object spread create new objects, so the signal gets a new array reference. Mutating t.done in place would not notify anyone, see Common Mistakes and Pitfalls.

Exercise 4 (Medium): a selection that survives only when valid

A size picker has a list of sizes and a selected size. When the list changes, keep the selection if it is still in the list; otherwise select the first size. The user can also choose a size directly.

Solution

TypeScript
readonly sizes = signal(['S', 'M', 'L']);

readonly selected = linkedSignal<string[], string>({
  source: this.sizes,
  computation: (sizes, previous) =>
    previous && sizes.includes(previous.value) ? previous.value : sizes[0],
});

selected.set('L') works like on any signal. A computed could not be assigned; a plain signal would never reset.

Exercise 5 (Hard): replace the effect

A component has celsius = signal(20) and an effect(() => this.fahrenheit.set(this.celsius() * 9 / 5 + 32)) that writes another signal. Improve it.

Solution: The value is derived, so it should be a computed:

TypeScript
readonly celsius = signal(20);
readonly fahrenheit = computed(() => (this.celsius() * 9) / 5 + 32);

Effects are for side effects that leave the signal graph: logging, drawing on a canvas, syncing with a non-Angular library. Copying one signal into another with an effect runs later than a computed, can briefly show inconsistent values and hides the dependency.

The first runnable example rebuilds exercises 1 to 5 with a tiny signal, computed and linked-signal stand-in.

TypeScript Signals exercises 1 to 5 with stand-ins

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.

Part 2: Templates (exercises 6 to 8)

Review: Pipes, Control Flow: @if, @for and @switch and Property, Attribute, Class and Style Binding.

Exercise 6 (Easy): format a price and a date

A component has price = signal(1234.5) and created = signal(new Date(2026, 0, 15)). Show the price as euros and the date as a medium date, using built-in pipes.

Solution

TypeScript
@Component({
  selector: 'app-invoice',
  imports: [CurrencyPipe, DatePipe],
  template: `
    <p>Total: {{ price() | currency: 'EUR' }}</p>
    <p>Created: {{ created() | date: 'mediumDate' }}</p>
  `,
})
export class Invoice {
  readonly price = signal(1234.5);
  readonly created = signal(new Date(2026, 0, 15));
}

Standalone components list the pipes they use in imports. The output depends on the app locale; with the default en-US locale it reads like Total: โ‚ฌ1,234.50 and Created: Jan 15, 2026.

Exercise 7 (Easy): a list with an empty state

Render items() as a list that shows the position (starting at 1), keeps row identity by id, and shows "Nothing here yet" when the list is empty.

Solution

HTML
<ul>
  @for (item of items(); track item.id; let i = $index) {
    <li>{{ i + 1 }}. {{ item.name }}</li>
  } @empty {
    <li>Nothing here yet</li>
  }
</ul>

track item.id lets Angular reuse the right DOM node when the list is reordered. $index is zero-based, so add one for people.

Exercise 8 (Medium): a toggle button done right

Make a button labelled "Done" that toggles a done signal. When done, it gets the CSS class done and tells assistive technology that it is pressed.

Solution

HTML
<button type="button"
        [class.done]="done()"
        [attr.aria-pressed]="done()"
        (click)="done.update(d => !d)">
  Done
</button>

[class.done] toggles one class, [attr.aria-pressed] sets the HTML attribute (ARIA has no matching DOM property to bind), and the event binding updates the signal.

Part 3: Dependency injection (exercises 9 to 11)

Review: Services and Dependency Injection and Providers, InjectionToken and Scopes.

Exercise 9 (Easy): a shared logger

Create a Logger service that stores messages and use it from two components so both see the same messages.

Solution

TypeScript
@Injectable({ providedIn: 'root' })
export class Logger {
  private readonly lines = signal<readonly string[]>([]);
  readonly messages = this.lines.asReadonly();

  log(message: string): void {
    this.lines.update(list => [...list, message]);
  }
}

// in any component
private readonly logger = inject(Logger);

providedIn: 'root' creates one application-wide instance, so every component that injects Logger gets the same object.

Exercise 10 (Medium): a configurable API address

Provide the API base URL through an InjectionToken with a sensible default, and override it for a staging build.

Solution

TypeScript
export const API_URL = new InjectionToken<string>('API_URL', {
  providedIn: 'root',
  factory: () => 'https://api.example.com',
});

// app.config.ts for the staging build
providers: [{ provide: API_URL, useValue: 'https://staging.example.com' }]

// anywhere
private readonly baseUrl = inject(API_URL);

A token is needed because a string has no class to use as a key. The factory gives the default; any provider closer to the consumer wins.

Exercise 11 (Medium): one counter per component instance

Two copies of <app-widget> on a page must each have their own CounterService, not share one.

Solution

TypeScript
@Injectable()
export class CounterService {
  readonly count = signal(0);
  increment(): void { this.count.update(n => n + 1); }
}

@Component({
  selector: 'app-widget',
  providers: [CounterService],
  template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class Widget {
  protected readonly counter = inject(CounterService);
}

Without providedIn, the service is created only where it is listed in providers. Each component instance gets its own element injector, so each owns a separate service object.

The second runnable example models exercises 9 to 11 with a mini injector hierarchy, and adds the route matcher for the routing exercises that follow.

TypeScript Dependency injection and routing exercises with stand-ins

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.

Notice how the staging injector answers for API_URL while the root still gives the default, and how the two widgets each get their own counter while the root's counter stays at 0. The route matcher shows redirects, a parameter and the wildcard that catches /products (one segment) and /x/y/z.

Part 4: Routing (exercises 12 to 14)

Review: Routing Basics, Route Parameters, Query Params and Navigation and Guards, Resolvers and Router Events.

Exercise 12 (Easy): a route table

Write the routes for a site with a home page, an about page, an empty path that goes to home, and a friendly page for unknown URLs.

Solution

TypeScript
export const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'home' },
  { path: 'home', title: 'Home', component: Home },
  { path: 'about', title: 'About', component: About },
  { path: '**', title: 'Page not found', component: NotFound },
];

The wildcard goes last, because the first match wins. pathMatch: 'full' keeps the redirect from capturing every URL.

Exercise 13 (Medium): a product page with a parameter

Add /products/:id. The detail component must receive the id without injecting ActivatedRoute, and the list must link to it.

Solution

TypeScript
// routes
{ path: 'products/:id', loadComponent: () => import('./product-detail').then(m => m.ProductDetail) }

// app.config.ts
provideRouter(routes, withComponentInputBinding())

// product-detail.ts
export class ProductDetail {
  readonly id = input.required<string>();
}
HTML
@for (p of products(); track p.id) {
  <a [routerLink]="['/products', p.id]">{{ p.name }}</a>
}

With withComponentInputBinding(), route params, query params and resolved data flow into inputs with the same name. Route parameters are strings, so convert with numberAttribute if you need a number.

Exercise 14 (Hard): do not lose unsaved work

A form page should ask for confirmation when the user navigates away with unsaved changes.

Solution

TypeScript
export interface HasUnsavedChanges {
  hasUnsavedChanges(): boolean;
}

export const leaveGuard: CanDeactivateFn<HasUnsavedChanges> = component =>
  !component.hasUnsavedChanges() || confirm('Leave without saving?');

// route
{ path: 'edit', component: EditPage, canDeactivate: [leaveGuard] }

// component
hasUnsavedChanges(): boolean {
  return this.form.dirty;
}

The guard receives the component instance, so it can ask it directly. A guard only covers in-app navigation: closing the tab needs a separate beforeunload listener. Design note: keep the dialog accessible; confirm() is the simplest choice, a custom dialog is the polished one.

Part 5: Forms (exercises 15 to 17)

Review: Reactive Forms, Validation and Custom Validators and Dynamic Forms and Custom Form Controls.

Exercise 15 (Easy): a sign-up form

Create a reactive form with a required, valid email and a password of at least 8 characters. Show a message for each problem, but only after the field was touched.

Solution

TypeScript
protected readonly form = inject(NonNullableFormBuilder).group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
});
HTML
<form [formGroup]="form" (ngSubmit)="submit()" novalidate>
  <input formControlName="email" type="email" />
  @if (form.controls.email.touched && form.controls.email.errors; as errors) {
    <p role="alert">{{ errors['required'] ? 'Email is required.' : 'Enter a valid email.' }}</p>
  }
  <input formControlName="password" type="password" />
  @if (form.controls.password.touched && form.controls.password.errors?.['minlength']) {
    <p role="alert">Use at least 8 characters.</p>
  }
  <button>Create account</button>
</form>

Exercise 16 (Medium): passwords must match

Add a "confirm password" field and make the whole group invalid when the two passwords differ.

Solution

TypeScript
const passwordsMatch: ValidatorFn = group =>
  group.get('password')?.value === group.get('confirm')?.value ? null : { mismatch: true };

protected readonly form = this.fb.group(
  {
    password: ['', [Validators.required, Validators.minLength(8)]],
    confirm: ['', Validators.required],
  },
  { validators: passwordsMatch },
);

A rule that compares two fields belongs to their parent group, so the validator receives the group. Read the error with form.errors?.['mismatch'].

Exercise 17 (Hard): a list of tags

Let the user add and remove tags. Every tag is required, and the form is invalid when any tag is empty or two tags are the same.

Solution

TypeScript
protected readonly tags = this.fb.array<FormControl<string>>([], {
  validators: control => {
    const values = control.value as string[];
    const unique = new Set(values).size === values.length;
    return unique ? null : { duplicate: true };
  },
});

protected addTag(): void {
  this.tags.push(this.fb.control('', Validators.required));
}

protected removeTag(index: number): void {
  this.tags.removeAt(index);
}
HTML
@for (tag of tags.controls; track tag; let i = $index) {
  <input [formControl]="tag" />
  <button type="button" (click)="removeTag(i)">Remove</button>
}

Track by the control object, not by the index, so the right input is reused when you remove one from the middle. Put tags in a FormGroup for submit, or bind it with formArrayName.

Part 6: RxJS (exercises 18 to 20)

Review: RxJS Essentials: Observables, RxJS Operators You Need and Signals and RxJS Interop.

Exercise 18 (Easy): even squares

From the numbers 1 to 6, emit only the squares of the even numbers.

Solution

TypeScript
of(1, 2, 3, 4, 5, 6)
  .pipe(
    filter(n => n % 2 === 0),
    map(n => n * n),
  )
  .subscribe(value => console.log(value));   // 4, 16, 36

Exercise 19 (Medium): a search that does not race

A search box emits text as the user types. Wait for a pause of 300 ms, ignore repeated text, and call the search service, so that a slow old answer can never replace a newer one.

Solution

TypeScript
this.results$ = this.term$.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(term => this.search.find(term)),
);

switchMap unsubscribes from the previous inner Observable when a new term arrives. With HttpClient that cancels the in-flight request. mergeMap would let old answers arrive late; concatMap would queue them. See the weather project in Project: Weather Dashboard with HttpClient.

Exercise 20 (Hard): clean up a subscription

A component has ngOnInit() { interval(1000).subscribe(n => this.ticks.set(n)); }. It keeps running after the component is gone. Fix it two ways.

Solution

TypeScript
// 1. Tie the subscription to the component's lifetime
private readonly destroyRef = inject(DestroyRef);

constructor() {
  interval(1000)
    .pipe(takeUntilDestroyed(this.destroyRef))
    .subscribe(n => this.ticks.set(n));
}

// 2. Better: let Angular subscribe and unsubscribe for you
readonly ticks = toSignal(interval(1000), { initialValue: 0 });

Inside an injection context such as a constructor, takeUntilDestroyed() needs no argument. Prefer toSignal or the async pipe when the value only feeds the template.

The third runnable example covers exercises 15 to 19: validators, a cross-field check, a tag list model and a tiny Observable with map, filter, debounceTime, distinctUntilChanged and switchMap.

TypeScript Forms and RxJS exercises with stand-ins

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.

The output shows each rule at work: empty and malformed emails fail with different error keys, the group validator catches mismatched passwords, and the tag list reports required and duplicate for two empty tags, only duplicate for two equal ones, and becomes valid once every tag is filled in and unique. In the search, five typed values produce only two searches, and the slow abc request is cancelled when abd takes over, so no stale answer can appear.

Where to go next

If you solved most exercises on your own, try the full applications in the project lessons, beginning with Project: Todo App with Signals. If you struggled with a part, repeat its lessons and then redo the exercises a few days later without looking at the solutions. For typical pitfalls, read Common Mistakes and Pitfalls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a computed signal a better fit than an effect for fahrenheit = celsius * 9 / 5 + 32?

    Derived state belongs in computed(). Effects are meant for side effects such as logging or integrating with non-Angular code.
  2. 2. Which providers give every instance of a component its own service object?

    Providers listed on a component create the service in that component's element injector, so each instance gets a separate object.
  3. 3. Where does a rule that compares two form fields belong?

    A cross-field validator needs to see both values, which the parent group can do. Its error is stored on the group.
  4. 4. Which operator prevents a slow old response from replacing a newer one in a search box?

    switchMap unsubscribes from the previous inner Observable when a new value arrives, which cancels an in-flight HTTP request.
  5. 5. Why track a FormArray's controls by the control object instead of the index?

    Index tracking would reuse the DOM of the last row after a removal, which can leave the wrong input focused or filled. Object identity follows the control.

Summary

  • Derived state is computed(), editable derived state is linkedSignal(), and effects are only for side effects.
  • Templates: built-in pipes, @for with track and @empty, and class and attribute bindings for state and accessibility.
  • Dependency injection: providedIn: 'root' for shared services, InjectionToken for values, component providers for per-instance services.
  • Routing: ordered route tables, withComponentInputBinding() for parameters, canDeactivate for unsaved changes.
  • Forms: group validators for cross-field rules, FormArray for lists, errors shown after touch.
  • RxJS: debounceTime, distinctUntilChanged and switchMap for search; tie subscriptions to the component lifetime or use toSignal.

Next: Common Mistakes and Pitfalls.