Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 74 ยท Projects

Project: Event Calendar

Build a month-view event calendar in Angular with a pure month-grid function, small components using input and output, the date pipe and safe persistence, with runnable stand-ins.

A calendar shows how much work hides behind a familiar screen. Before you draw anything, you need to answer: how many days does this month have, on which weekday does it start, and how do you fill the leading and trailing blanks? The answer is a small, pure function, and everything else (events, selection, navigation) is ordinary Angular.

This project uses Inputs and Outputs, Pipes, Control Flow and signals. The plan: build the month grid as data, show it with two small components, attach events to days, and persist them.

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 grid logic in TypeScript, and one is a working calendar UI in plain JavaScript. The sandbox has no localStorage, so events live in memory.

Step 1: the plan

  • The view is one month, held in a signal as { year, month } (month 0 to 11, like JavaScript Date).
  • The grid is a list of weeks; each week has seven cells. A cell is either empty (padding) or a day with a date key such as 2026-05-14.
  • Events are stored by date key: { id, date, title }.
  • Keys are strings in YYYY-MM-DD form, built from numbers, not from toISOString(). toISOString() converts to UTC and can shift the day by one in some time zones, a classic calendar bug.
flowchart TD
  M["month signal<br/>{ year, month }"] --> G["buildMonthGrid()<br/>weeks of cells"]
  E["EventStore<br/>events by date"] --> V["CalendarPage"]
  G --> V
  V --> D["DayCell (input: day, events)<br/>output: select"]

The grid is computed from the month; the page combines it with events and passes each day to a small component.

Step 2: the grid function

TypeScript
// calendar-grid.ts
export interface DayCell {
  key: string;   // "2026-05-14"
  day: number;   // 14
}
export type Week = (DayCell | null)[];

export function dateKey(year: number, month: number, day: number): string {
  const mm = String(month + 1).padStart(2, '0');
  const dd = String(day).padStart(2, '0');
  return `${year}-${mm}-${dd}`;
}

export function buildMonthGrid(year: number, month: number, weekStartsOn: 0 | 1 = 0): Week[] {
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const firstWeekday = new Date(year, month, 1).getDay(); // 0 = Sunday
  const offset = (firstWeekday - weekStartsOn + 7) % 7;

  const cells: (DayCell | null)[] = Array(offset).fill(null);
  for (let day = 1; day <= daysInMonth; day++) {
    cells.push({ key: dateKey(year, month, day), day });
  }
  while (cells.length % 7 !== 0) cells.push(null);

  const weeks: Week[] = [];
  for (let i = 0; i < cells.length; i += 7) weeks.push(cells.slice(i, i + 7));
  return weeks;
}

new Date(year, month + 1, 0) is a handy trick: day 0 of the next month is the last day of this month, so getDate() returns the number of days, leap years included. The offset formula turns a Sunday-based weekday into one based on the week start you choose.

Step 3: the store and the components

The store holds events by date and saves them; the pattern is the one from the Todo project.

TypeScript
// event-store.ts
import { computed, effect, Injectable, signal } from '@angular/core';

export interface CalendarEvent { id: number; date: string; title: string }
const KEY = 'calendar-events-v1';

@Injectable({ providedIn: 'root' })
export class EventStore {
  private readonly items = signal<CalendarEvent[]>(this.load());
  private nextId = Math.max(0, ...this.items().map(e => e.id)) + 1;

  readonly byDate = computed(() => {
    const map = new Map<string, CalendarEvent[]>();
    for (const e of this.items()) map.set(e.date, [...(map.get(e.date) ?? []), e]);
    return map;
  });

  constructor() {
    effect(() => {
      try { localStorage.setItem(KEY, JSON.stringify(this.items())); } catch { /* no storage */ }
    });
  }

  add(date: string, title: string): void {
    const clean = title.trim();
    if (!clean) return;
    this.items.update(list => [...list, { id: this.nextId++, date, title: clean }]);
  }

  remove(id: number): void {
    this.items.update(list => list.filter(e => e.id !== id));
  }

  private load(): CalendarEvent[] {
    try {
      const data: unknown = JSON.parse(localStorage.getItem(KEY) ?? '[]');
      return Array.isArray(data)
        ? data.filter((e): e is CalendarEvent =>
            typeof e?.id === 'number' && typeof e?.date === 'string' && typeof e?.title === 'string')
        : [];
    } catch {
      return [];
    }
  }
}

A day cell is a presentational component: it receives one cell and its events and reports a click.

TypeScript
// day-cell.ts
import { Component, input, output } from '@angular/core';
import { CalendarEvent } from './event-store';
import { DayCell } from './calendar-grid';

@Component({
  selector: 'app-day-cell',
  template: `
    @if (cell(); as c) {
      <button type="button" class="day" [class.selected]="selected()" (click)="pick.emit(c.key)">
        <span>{{ c.day }}</span>
        @for (e of events(); track e.id) { <small>{{ e.title }}</small> }
      </button>
    }
  `,
})
export class DayCellComponent {
  cell = input.required<DayCell | null>();
  events = input<CalendarEvent[]>([]);
  selected = input(false);
  pick = output<string>();
}

The page owns the month signal, the selection, and the form for a new event. The date pipe formats the heading and the selected day (Pipes).

TypeScript
// calendar-page.ts
import { Component, computed, inject, signal } from '@angular/core';
import { DatePipe } from '@angular/common';
import { buildMonthGrid } from './calendar-grid';
import { DayCellComponent } from './day-cell';
import { EventStore } from './event-store';

@Component({
  selector: 'app-calendar-page',
  imports: [DatePipe, DayCellComponent],
  template: `
    <header>
      <button type="button" (click)="move(-1)" aria-label="Previous month">&lt;</button>
      <h2>{{ firstOfMonth() | date: 'MMMM yyyy' }}</h2>
      <button type="button" (click)="move(1)" aria-label="Next month">&gt;</button>
    </header>

    <div class="grid" role="grid">
      @for (week of weeks(); track $index) {
        <div role="row" class="week">
          @for (cell of week; track $index) {
            <app-day-cell [cell]="cell" [events]="cell ? (store.byDate().get(cell.key) ?? []) : []"
                          [selected]="cell?.key === selected()" (pick)="selected.set($event)" />
          }
        </div>
      }
    </div>

    @if (selected(); as key) {
      <h3>Events on {{ key | date: 'fullDate' }}</h3>
      <input #title aria-label="Event title" (keydown.enter)="add(key, title)" />
      <button type="button" (click)="add(key, title)">Add event</button>
    }
  `,
})
export class CalendarPage {
  protected readonly store = inject(EventStore);
  protected readonly view = signal({ year: 2026, month: 4 });
  protected readonly selected = signal<string | null>(null);

  protected readonly weeks = computed(() => buildMonthGrid(this.view().year, this.view().month));
  protected readonly firstOfMonth = computed(() => new Date(this.view().year, this.view().month, 1));

  protected move(delta: number): void {
    this.view.update(({ year, month }) => {
      const d = new Date(year, month + delta, 1);
      return { year: d.getFullYear(), month: d.getMonth() };
    });
  }

  protected add(key: string, box: HTMLInputElement): void {
    this.store.add(key, box.value);
    box.value = '';
  }
}

Moving between months uses new Date(year, month + delta, 1), which rolls over correctly: month 12 becomes January of the next year, month -1 becomes December of the previous one. track $index is fine for the grid because the cells have no identity of their own.

Use date: 'MMMM yyyy' with Angular's DatePipe rather than hand-writing month names. The pipe follows the app's locale, which matters for Internationalization.

Step 4: run the grid logic

The first stand-in runs buildMonthGrid for months that are easy to get wrong: February in a leap year, a month that starts on a Sunday, and one that needs six weeks. weekStartsOn shows how the offset changes.

TypeScript Building a month grid

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 grid always has a multiple of seven cells, so the template never needs special cases. August 2026 starts on a Saturday and needs six rows; February 2026 starts on a Sunday, so with a Monday start the first row has six blank cells before the 1st.

Step 5: see it as a UI

The second stand-in is a complete calendar in plain JavaScript: it renders the grid, lets you move between months, select a day and add events.

A working event calendar

Ideas to extend it

  • Highlight today by comparing each cell's key with a key built from new Date().
  • Let events have a start time and sort each day's list.
  • Switch the first weekday with a signal and pass it to buildMonthGrid.
  • Add a week view that reuses DayCellComponent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How can you get the number of days in a month with the Date constructor?

    Day 0 of the next month is the last day of the current month, so getDate() returns the month's length, leap years included.
  2. 2. Why build date keys from year, month and day numbers instead of toISOString()?

    A local date at midnight can fall on the previous or next day in UTC. Building the key from local parts avoids the shift.
  3. 3. What is the role of DayCellComponent in this design?

    Small components that only display data and emit events are easy to reuse and test, while the page owns the state.
  4. 4. Why does the grid pad with null cells up to a multiple of seven?

    Leading and trailing blanks keep the weekday columns aligned and make rendering uniform.

Summary

  • Compute the month grid with a pure function that returns weeks of day cells and null padding.
  • Use new Date(year, month + 1, 0).getDate() for the month length and new Date(year, month + delta, 1) to move between months.
  • Build YYYY-MM-DD keys from local numbers, not toISOString().
  • Keep events in a signal store grouped by date with computed(), validate them when loading, and pass each day to a presentational component with input() and output().
  • Format headings with the date pipe so the calendar follows the app's locale.

Next: Project: Movie Search App.