TExcelTAD
Home › Angular › Angular Exercises

Angular Exercises

Time to practise. Each task below states a goal and a few hints. Try it yourself first — in a local project created with ng new practice — then open the solution to compare. Tasks 1 and 2 are plain TypeScript, so you can solve them right here in the playground.

Exercise 1: A slugify pipe (plain TypeScript)

Write the transform method of a pipe that turns a title into a URL slug: lowercase, trimmed, spaces and punctuation replaced by single dashes, no leading or trailing dash. Edit the playground until the output matches.

ts · try it yourself
class SlugifyPipe {
  transform(value: string): string {
    // TODO: replace this line with your implementation
    return value.toLowerCase();
  }
}

const slug = new SlugifyPipe();
console.log(slug.transform('  Hello, Angular World! '));
console.log(slug.transform('Signals & Effects -- Part 2'));
  hello, angular world! 
signals & effects -- part 2

The expected result after your fix is hello-angular-world and signals-effects-part-2.

Show solution
ts
class SlugifyPipe {
  transform(value: string): string {
    return value
      .toLowerCase()
      .trim()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');
  }
}

Exercise 2: A tiny store with derived state (plain TypeScript)

Complete TodoStore so that remaining() returns the number of unfinished todos and toggle(id) flips one todo's done flag immutably (create a new array).

ts · try it yourself
interface Todo { id: number; title: string; done: boolean; }

class TodoStore {
  todos: Todo[] = [
    { id: 1, title: 'Read the signals lesson', done: true },
    { id: 2, title: 'Build a component', done: false },
    { id: 3, title: 'Write a test', done: false },
  ];

  remaining(): number {
    return 0; // TODO
  }

  toggle(id: number): void {
    // TODO
  }
}

const store = new TodoStore();
const before = store.todos;
store.toggle(2);
console.log('remaining:', store.remaining());
console.log('new array?', store.todos !== before);
remaining: 0
new array? false

When it works, the output is remaining: 1 and new array? true.

Show solution
ts
remaining(): number {
  return this.todos.filter((t) => !t.done).length;
}

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

Exercise 3: Counter component

Create a standalone Counter component with −, + and Reset buttons. The count must never go below 0, and the number should turn red when it reaches 10 or more.

Hints: signal(), update(), [class.x] or [style.color].

Show solution
ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="dec()">−</button>
    <span [style.color]="count() >= 10 ? 'red' : 'inherit'">{{ count() }}</span>
    <button (click)="count.update((c) => c + 1)">+</button>
    <button (click)="count.set(0)">Reset</button>
  `,
})
export class Counter {
  count = signal(0);
  dec() {
    this.count.update((c) => Math.max(0, c - 1));
  }
}

Exercise 4: Filterable list

Show a list of fruits and a text input. As the user types, only fruits containing the text (case-insensitive) are shown. When nothing matches, show "No results".

Hints: a query signal, a computed() for the filtered list, @for with @empty.

Show solution
ts
import { Component, computed, signal } from '@angular/core';

@Component({
  selector: 'app-fruit-filter',
  template: `
    <input placeholder="Filter…" (input)="query.set($any($event.target).value)" />
    <ul>
      @for (f of filtered(); track f) {
        <li>{{ f }}</li>
      } @empty {
        <li>No results</li>
      }
    </ul>
  `,
})
export class FruitFilter {
  fruits = ['Apple', 'Banana', 'Mango', 'Durian', 'Papaya'];
  query = signal('');
  filtered = computed(() => {
    const q = this.query().toLowerCase();
    return this.fruits.filter((f) => f.toLowerCase().includes(q));
  });
}

Exercise 5: Parent and child communication

Build a ColorPicker child that receives a list of colours as a required input and emits the chosen colour through an output. The parent displays a square in the selected colour.

Show solution
ts
import { Component, input, output, signal } from '@angular/core';

@Component({
  selector: 'app-color-picker',
  template: `
    @for (c of colors(); track c) {
      <button [style.background]="c" (click)="picked.emit(c)">{{ c }}</button>
    }
  `,
})
export class ColorPicker {
  colors = input.required<string[]>();
  picked = output<string>();
}

@Component({
  selector: 'app-root',
  imports: [ColorPicker],
  template: `
    <app-color-picker [colors]="['tomato', 'gold', 'teal']" (picked)="color.set($event)" />
    <div [style.background]="color()" style="width: 80px; height: 80px"></div>
  `,
})
export class App {
  color = signal('tomato');
}

Exercise 6: A shared service

Create a NotificationService (provided in root) with a messages signal and push(text) / dismiss(index) methods. Use it from two components: one with a button that pushes a message, one that lists messages with a ✕ to dismiss them.

Show solution
ts
@Injectable({ providedIn: 'root' })
export class NotificationService {
  private readonly _messages = signal<string[]>([]);
  readonly messages = this._messages.asReadonly();

  push(text: string) {
    this._messages.update((m) => [...m, text]);
  }

  dismiss(index: number) {
    this._messages.update((m) => m.filter((_, i) => i !== index));
  }
}

@Component({
  selector: 'app-notify-button',
  template: `<button (click)="notes.push('Saved at step ' + (notes.messages().length + 1))">Save</button>`,
})
export class NotifyButton {
  protected notes = inject(NotificationService);
}

@Component({
  selector: 'app-notification-list',
  template: `
    @for (m of notes.messages(); track $index) {
      <p>{{ m }} <button (click)="notes.dismiss($index)">✕</button></p>
    }
  `,
})
export class NotificationList {
  protected notes = inject(NotificationService);
}

Exercise 7: Reactive login form

Build a login form with email (required, valid email) and password (required, min 8 characters). Disable the submit button while the form is invalid and show an error under each field once it is touched.

Show solution
ts
@Component({
  selector: 'app-login',
  imports: [ReactiveFormsModule],
  template: `
    <form [formGroup]="form" (ngSubmit)="login()">
      <input formControlName="email" placeholder="Email" />
      @if (form.controls.email.touched && form.controls.email.invalid) {
        <small>Enter a valid email.</small>
      }
      <input formControlName="password" type="password" placeholder="Password" />
      @if (form.controls.password.touched && form.controls.password.invalid) {
        <small>At least 8 characters.</small>
      }
      <button [disabled]="form.invalid">Log in</button>
    </form>
  `,
})
export class Login {
  form = inject(FormBuilder).nonNullable.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', [Validators.required, Validators.minLength(8)]],
  });

  login() {
    console.log(this.form.getRawValue());
  }
}

Exercise 8: Routes with a parameter and a guard

Add routes for /users (list) and /users/:id (detail, reading id as a number input). Protect /users/:id with a functional guard that only allows access when an Auth service's loggedIn() signal is true; otherwise redirect to /login.

Show solution
ts
// app.routes.ts
export const loggedInGuard: CanActivateFn = () =>
  inject(Auth).loggedIn() ? true : inject(Router).createUrlTree(['/login']);

export const routes: Routes = [
  { path: 'users', component: UserList },
  { path: 'users/:id', component: UserDetail, canActivate: [loggedInGuard] },
  { path: 'login', component: Login },
];

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

// user-detail.ts
export class UserDetail {
  id = input.required({ transform: numberAttribute });
}

Exercise 9: Lazy-load a heavy widget

A page shows an article. At the bottom there's a CommentsSection component. Make sure its code is only downloaded when the user scrolls near it, with a placeholder text before that and a loading message that stays at least 300 ms.

Show solution
html
<article>…</article>

@defer (on viewport) {
  <app-comments-section [articleId]="article().id" />
} @placeholder {
  <p>Comments</p>
} @loading (minimum 300ms) {
  <p>Loading comments…</p>
}

Test yourself

In Exercise 4, why is filtered a computed() rather than a method called from the template?

  1. Methods are not allowed in templates
  2. computed caches the result and only recalculates when query changes
  3. computed runs on the server
  4. It makes the list sortable

In Exercise 6, why is _messages private with a public asReadonly() view?

  1. Private signals render faster
  2. So only the service can change the state, keeping updates in one place
  3. Templates can't read writable signals
  4. It is required by providedIn: 'root'