English
The application skeleton
Step 1. The source folders
Why. The backend is split into projects whose references point one way only (topic 2). The client is one Angular project, so the same discipline is kept by folders under src/app (Table 15.6, Fig. 15.2).
Table 15.6. The folders of src/app
| Folder | Contains | May use | Topics |
|---|---|---|---|
core/ | singletons without a user interface: api (HTTP services, DTO models, problem details), auth (session, interceptor, guards), realtime (SignalR, presence, typing), media (protected files as blob URLs), ui (theme, toasts) | other core/ folders | 15–20 |
state/ | the signal stores ChatsStore and MessagesStore | core/ | 18–20 |
shared/ui/ | small reusable components and helpers: icons, avatar, dialogs, user search, pipes | core/ | 15–18 |
features/ | pages and dialogs, one folder per feature: auth, shell, chat-list, conversation, chat-info, new-chat, discover, settings, user-profile | everything above, and other features' dialogs | 17–21 |
Fig. 15.2. Dependencies between the folders
The file names follow the Angular style guide of 2025, which ng new used: login.page.ts for a page, theme.service.ts for a service, shell.ts for a component, chats.store.ts for a store, problem.spec.ts for the tests of problem.ts. Class names drop the old suffixes: the root component is App, not AppComponent.
Git does not store empty folders, so the folders appear as the files arrive. The first two are created in this chapter.
Step 2. Bootstrapping without zone.js
Why. A C# program starts in Program.cs, builds a host with its services and runs it. An Angular application does the same in src/main.ts: bootstrapApplication creates the root injector from a list of providers and renders the root component into <app-root>.
Do. main.ts stays as generated; after npm run format it is identical to the reference:
ts
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
bootstrapApplication(App, appConfig).catch((err) => console.error(err));The providers come from app.config.ts. For now it keeps the generated content, formatted by Prettier:
ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideBrowserGlobalErrorListeners(), provideRouter(routes)],
};provideBrowserGlobalErrorListeners()reports errors that escape event handlers and promises to Angular'sErrorHandler, which logs them to the console.provideRouter(routes)registers the router with the routes ofapp.routes.ts, an empty array for now. Topic 17 fills it; topic 16 replacesapp.config.tswith its final version.- What is missing is as important. Older applications called
provideZoneChangeDetection()and loadedzone.jsinpolyfills. A zoneless application has neither:package.jsonhas nozone.js, andangular.jsonhas nopolyfills.
Change detection with and without zone.js
Angular has to know when to update the DOM. For years it used zone.js, a library that patches every asynchronous browser API — setTimeout, addEventListener, fetch, promises — and tells Angular "something may have changed" after each of them. Angular then checked every component of the tree. It worked without any effort from the developer, but it cost an extra download, extra work after every timer and mouse move, and stack traces full of zone frames.
Zoneless Angular is told explicitly. A component is checked when a signal that its template reads changes, when an event handler of its template runs, when one of its inputs changes, or when code calls markForCheck(). With signals everywhere — as in Chatex — this is automatic and precise: changing one message's text re-renders exactly the bindings that read it. The price is a rule: state that the template shows must be a signal (or come from a signal, an input or the async pipe). A plain field changed in a setTimeout is not shown until something else triggers a check.
Step 3. The icon set
Why. Chatex uses icons from Lucide, an open-source set of clean line icons. @lucide/angular ships every icon as a standalone component that renders an inline <svg>. Importing only the icons we need keeps the bundle small, and keeping them in one list lets every component import one constant.
Do. Create the list:
ts
import {
LucideArrowDown,
LucideArrowLeft,
LucideBell,
LucideBellOff,
LucideCamera,
LucideCheck,
LucideCheckCheck,
LucideCircleExclamationPoint,
LucideCompass,
LucideCopy,
LucideCrown,
LucideDownload,
LucideEllipsisVertical,
LucideFile,
LucideFileText,
LucideGlobe,
LucideInfo,
LucideKeyRound,
LucideLoaderCircle,
LucideLock,
LucideLogOut,
LucideMegaphone,
LucideMessagesSquare,
LucideMonitor,
LucideMoon,
LucidePaperclip,
LucidePencil,
LucidePlus,
LucideReply,
LucideRotateCw,
LucideSearch,
LucideSend,
LucideSettings,
LucideShield,
LucideSquarePen,
LucideSun,
LucideTrash,
LucideUser,
LucideUserMinus,
LucideUserPlus,
LucideUsers,
LucideWifiOff,
LucideX,
} from '@lucide/angular';
/** Every icon the app uses; import this array into a component to use `<svg lucideXxx class="size-5" />`. */
export const ICONS = [
LucideArrowDown,
LucideArrowLeft,
LucideBell,
LucideBellOff,
LucideCamera,
LucideCheck,
LucideCheckCheck,
LucideCircleExclamationPoint,
LucideCompass,
LucideCopy,
LucideCrown,
LucideDownload,
LucideEllipsisVertical,
LucideFile,
LucideFileText,
LucideGlobe,
LucideInfo,
LucideKeyRound,
LucideLoaderCircle,
LucideLock,
LucideLogOut,
LucideMegaphone,
LucideMessagesSquare,
LucideMonitor,
LucideMoon,
LucidePaperclip,
LucidePencil,
LucidePlus,
LucideReply,
LucideRotateCw,
LucideSearch,
LucideSend,
LucideSettings,
LucideShield,
LucideSquarePen,
LucideSun,
LucideTrash,
LucideUser,
LucideUserMinus,
LucideUserPlus,
LucideUsers,
LucideWifiOff,
LucideX,
] as const;A component puts ICONS into its imports and writes <svg lucideSend class="size-5"></svg> in its template. The attribute lucideSend selects the component that draws the icon; Tailwind's size-5 makes it 20 × 20 px, and text-* colours it, because the icons draw with currentColor. as const turns the array into a read-only tuple, which Angular accepts in imports.
Step 4. Signals and the theme service
Why. The first service of the client keeps the theme: light, dark or "follow the system". It is a good first example of signals, because the theme is state that the page must show and that changes from three sides — the user's choice, a saved preference and the operating system.
Do. Create the service:
ts
import { DOCUMENT, Injectable, computed, effect, inject, signal } from '@angular/core';
export type ThemePreference = 'light' | 'dark' | 'system';
export const THEME_STORAGE_KEY = 'chatex.theme';
/** Light, dark or follow the OS. The choice is kept per browser; index.html applies it before paint. */
@Injectable({ providedIn: 'root' })
export class ThemeService {
private readonly document = inject(DOCUMENT);
private readonly media = this.document.defaultView?.matchMedia?.('(prefers-color-scheme: dark)');
private readonly systemDark = signal(this.media?.matches ?? false);
readonly preference = signal<ThemePreference>(this.load());
readonly isDark = computed(() => {
const preference = this.preference();
return preference === 'dark' || (preference === 'system' && this.systemDark());
});
constructor() {
this.media?.addEventListener?.('change', (event) => this.systemDark.set(event.matches));
effect(() => {
const dark = this.isDark();
this.document.documentElement.classList.toggle('dark', dark);
this.document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', dark ? '#18181b' : '#4f46e5');
});
}
set(preference: ThemePreference): void {
this.preference.set(preference);
try {
localStorage.setItem(THEME_STORAGE_KEY, preference);
} catch {
// Storage can be blocked; the choice then lasts for this tab only.
}
}
private load(): ThemePreference {
try {
const saved = localStorage.getItem(THEME_STORAGE_KEY);
return saved === 'light' || saved === 'dark' ? saved : 'system';
} catch {
return 'system';
}
}
}@Injectable({ providedIn: 'root' })registers the class as a singleton in the root injector, the equivalent ofservices.AddSingleton<ThemeService>(). It is created the first time someone injects it, and tree-shaken away if nobody does.inject(DOCUMENT)is Angular's dependency injection as a function call. It works in field initializers and constructors of classes that Angular creates. InjectingDOCUMENTinstead of using the globaldocumentkeeps the service testable and usable outside a browser.signal(value)creates a writable signal. Reading it is a call —this.preference()— and writing isset(value)orupdate(fn).ThemePreferenceis a union of string literals: TypeScript allows exactly'light','dark'or'system', like an enum whose values are the strings themselves.computed(fn)derives a read-only signal.isDarkreadspreferenceandsystemDark; Angular records these dependencies and recomputesisDarkonly when one of them changes, caching the result in between.effect(fn)runs a side effect whenever the signals it read change: here it toggles the classdarkon<html>and recolours the browser bar. Effects are for synchronising signals with the outside world (the DOM, storage); they should not set other signals.- The OS setting is a
matchMediaquery. Itschangeevent updatessystemDark, so a user on "system" who switches the OS to dark at sunset gets the dark theme at once. setsaves the choice inlocalStorageunder the same key thattheme-init.jsreads at the next start.loadaccepts only the two valid values, so a damaged entry means "system".
Signals for a C# developer
A signal is like a property of a view model that raises PropertyChanged, with two differences: the dependencies are discovered automatically by calling the getter, and derived values (computed) are lazy and cached. There is no INotifyPropertyChanged boilerplate and no string with the property name. Angular uses signals for state that the user interface shows; RxJS observables, which you will meet in topic 16, remain the tool for streams of events such as HTTP responses or hub messages.
Now the first test of the client:
ts
import { TestBed } from '@angular/core/testing';
import { THEME_STORAGE_KEY, ThemeService } from './theme.service';
describe('ThemeService', () => {
beforeEach(() => {
localStorage.clear();
document.documentElement.classList.remove('dark');
});
it('follows the system by default', () => {
const theme = TestBed.inject(ThemeService);
expect(theme.preference()).toBe('system');
});
it('switches to dark, toggles the html class and remembers the choice', () => {
const theme = TestBed.inject(ThemeService);
theme.set('dark');
TestBed.tick();
expect(theme.isDark()).toBe(true);
expect(document.documentElement.classList.contains('dark')).toBe(true);
expect(localStorage.getItem(THEME_STORAGE_KEY)).toBe('dark');
theme.set('light');
TestBed.tick();
expect(document.documentElement.classList.contains('dark')).toBe(false);
});
it('loads the saved choice', () => {
localStorage.setItem(THEME_STORAGE_KEY, 'dark');
expect(TestBed.inject(ThemeService).preference()).toBe('dark');
});
});beforeEachresets the shared state, because jsdom keepslocalStorageand the<html>element between tests.TestBed.inject(ThemeService)creates the service in a fresh test injector.TestBed.tick()runs pending effects. Effects are scheduled, not run synchronously when a signal changes; in the application, Angular runs them during change detection, and in a testtick()does it.
Step 5. The root component
Why. The generated root component shows Angular's welcome page from app.html, with an empty app.css and a test for the welcome text. Chatex's root component is just a frame: a <router-outlet>, where the router puts the current page, and, from topic 17, the toasts.
Do. Delete the generated template, style and test:
powershell
Remove-Item src/app/app.html, src/app/app.css, src/app/app.spec.tsReplace app.ts. The two lines in yellow are temporary: topic 17 adds the toaster to them.
angular-ts
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ThemeService } from './core/ui/theme.service';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<router-outlet />`,
})
export class App {
constructor() {
// Created eagerly so the saved theme and OS changes apply on every page.
inject(ThemeService);
}
}@Componentis a decorator — an attribute that runs code — that turns the class into a component.selector: 'app-root'is the element inindex.htmlwhere Angular renders it.imports: [RouterOutlet]lists what the template uses. A standalone component compiles its template against exactly this list; using<router-outlet>without importingRouterOutletis a compile error.ChangeDetectionStrategy.OnPush— every component in Chatex uses it: the component is checked only when its inputs, its events or its signals say so (the rules of the zoneless box above), never just because something somewhere changed.templateis written inline in a template literal (backticks). For the small templates of Chatex this keeps the class and its markup in one file; the Angular Language Service still type-checks it.inject(ThemeService)in the constructor creates the theme service at start-up, so its effect applies the saved theme and follows the OS on every page, even before any page uses the service.
Check
powershell
npm test -- --watch=false Test Files 1 passed (1)
Tests 3 passed (3)npm run build, npm run lint and npm run format:check succeed as well.
Step 6. The development proxy
Why. In production, Nginx serves the Angular files and forwards /api and /hubs to the API, so the browser sees one origin (topic 24). In development, the Angular dev server runs on http://localhost:4200 and the API on http://localhost:5214: two origins. The refresh token travels in an HttpOnly cookie restricted to the API's path (topic 13), and cross-origin calls would need CORS and cookies with SameSite=None. The simpler and more faithful solution is to give development the same shape as production: the dev server forwards API calls, and the browser talks to one origin only.
Do. Create the proxy configuration, which angular.json already references:
json
{
"/api": {
"target": "http://localhost:5214",
"secure": false,
"changeOrigin": false
},
"/hubs": {
"target": "http://localhost:5214",
"secure": false,
"ws": true
}
}/apirequests are forwarded to the API.changeOrigin: falsekeeps theHostheader of the browser's request./hubsalso forwards WebSocket upgrades (ws: true): SignalR's connection to/hubs/chat(topic 20) goes through the proxy too.secure: falsewould accept a self-signed certificate if the target were HTTPS; the API runs on plain HTTP in development.
Start the API in one terminal, from the repository root:
powershell
./Run.ps1 apiand the client in a second one:
powershell
./Run.ps1 web ➜ Local: http://localhost:4200/
➜ press h + enter to show helpCheck
Open
http://localhost:4200. The page is empty, but it has the title "Chatex", the Chatex icon in the tab, and the canvas colour of your OS theme: switch the OS between light and dark, and the page follows. In the browser's developer tools (F12), the<html>element has the classdarkin the dark theme.Run
localStorage.setItem('chatex.theme', 'light')in the console and reload: the page stays light even with a dark OS.localStorage.removeItem('chatex.theme')returns to "system".In a third terminal, call the API through the proxy:
powershellcurl.exe -i http://localhost:4200/api/meThe first line is
HTTP/1.1 401 Unauthorized: the request reached the API, which wants a token. Without the proxy, the dev server would answer200 OKwithindex.html, its fallback for unknown paths.