How do you structure a new Angular application from scratch with at least five feature modules?
Show answer · architecture diagram, dependency rule, routing, guards, interceptors, state, quality gates, follow-ups
I start from the boundaries of the domain, not from the framework. Before writing code I list the business capabilities the product sells — for this client that would be dashboard, shipments, billing, reports, admin — and each capability becomes one lazily loaded feature. Everything that is not a capability goes into three technical buckets: core/ (singletons), shared/ (stateless reuse), layout/ (the shell). The rule that makes the structure real is a dependency rule a reviewer can enforce in a pull request: features may import from core and shared; shared never imports a feature; core imports neither.
The dependency rule, written down
A folder diagram is decoration unless it comes with a rule and a way to fail the build when the rule breaks. This is the table I put in the repository's README or ARCHITECTURE.md:
| Importer | May import core/ | May import shared/ | May import another feature |
|---|---|---|---|
| core/ | — | No | No |
| shared/ | Only tokens and types | — | No |
| features/<x> | Yes | Yes | No — move the contract to core/ |
| app shell | Yes | Yes | Only through a lazy route, never by importing internals |
Enforcement is cheap if it exists from day one: @typescript-eslint with no-restricted-imports patterns, or dependency-cruiser with a forbidden rule, plus a CI step that fails on a violation. A written rule that only lives in a wiki is a rule that lasts until the first Friday deadline.
1 · Bootstrap: what happens before the first pixel
index.htmlloadsmain.ts. With standalone bootstrapping the entry point is one call:bootstrapApplication(AppComponent, appConfig).- Runtime configuration is loaded before render — an
APP_INITIALIZER(orprovideAppInitializerin newer versions) fetchesassets/config.jsonwith the API base URL and feature flags. That is what lets the same built artefact be promoted from QA to production instead of rebuilding per environment. - The global
ErrorHandleris registered before any route resolves, so a failure in a resolver is reported with the same shape as a failure in a click handler. - The shell renders: header, navigation, breadcrumbs, toast host and a single
<router-outlet>. The shell never fetches feature data; it owns layout and session chrome. - The initial route is the only feature that can be part of the main chunk. Everything else waits for the user to navigate.
2 · Routing is the architecture
The root router declares the shell and one entry per capability. Two guard types do different jobs and it is worth being precise about them, because the difference is measurable in kilobytes: canMatch runs before the lazy chunk is downloaded, canActivate runs after it loads. A role check belongs in canMatch, otherwise an unauthorised user downloads the module they will never see.
// app.routes.ts — the shell declares features, never their internals
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'dashboard' },
{
path: 'dashboard',
loadChildren: () => import('./features/dashboard/dashboard.routes').then(m => m.DASHBOARD_ROUTES),
canActivate: [authGuard]
},
{
path: 'shipments',
loadChildren: () => import('./features/shipments/shipments.routes').then(m => m.SHIPMENTS_ROUTES),
canMatch: [roleMatchGuard(['ops', 'pricing'])], // Angular 14+: no chunk download for the wrong role
canActivate: [authGuard],
resolve: { reference: referenceDataResolver }
},
{
path: 'billing',
loadChildren: () => import('./features/billing/billing.routes').then(m => m.BILLING_ROUTES),
canMatch: [roleMatchGuard(['billing-admin'])],
data: { title: 'Billing' }
},
{ path: '**', component: NotFoundComponent }
];
Three decisions around routing that I make at setup rather than later:
- Preloading strategy.
PreloadAllModulesis fine for five small features; with heavy reporting or mapping libraries I use a custom strategy that preloads only the routes the current user's role can reach, and never on a metered connection. - Route-level providers. A feature declares its own service instances (
providers: [ShipmentStore]) so leaving the route disposes them. That is the cheapest way to avoid leaks in a long-lived SPA. - Titles, scroll and breadcrumbs come from router events once, in the shell, not from each component.
3 · Guards: four jobs, four places
| Guard | Question it answers | Where it lives |
|---|---|---|
canMatch | Does this route exist for this user at all? | Root, next to the lazy entry |
canActivate | May this user enter this screen? | Feature route |
canDeactivate | Can the user leave with unsaved work? | On the form route |
resolve | What data does the screen need to render once? | Feature route |
Two details that separate a working guard from a bug report: a guard must complete (first(), take(1) or a promise) because an observable that emits twice cancels and re-runs navigation; and a guard is a UX boundary, not a security boundary — the API authorises every request again, because the browser is the user's machine.
4 · The interceptor chain is ordered on purpose
// app.config.ts — order is a design decision, not an accident
provideHttpClient(
withInterceptors([
authTokenInterceptor, // 1. attach the bearer token
refreshOn401Interceptor, // 2. refresh once, then replay the request
retryIdempotentInterceptor,// 3. retry GETs with backoff, never POSTs
correlationIdInterceptor, // 4. one id per request, echoed in the response
errorNormalizerInterceptor // 5. map ProblemDetails to a domain error
])
)
For a request the array reads top-down; for the response it unwinds bottom-up. That is why the refresh sits inside the token interceptor: the replayed request has to pass through it again to pick up the new token. And it is why error normalisation is last — every failure, including a failed refresh, arrives at the same shape and the same toast.
5 · State: local first, shared only when it is shared
- Component state — signals or plain fields. Most of the state in a business application is this.
- Feature state — a service provided at the feature route, holding the list, the filters and the selected record. It dies when the user leaves the feature.
- Cross-feature state — a small facade in
core/with an explicit interface: session, permissions, tenant, reference data. Features subscribe to it; they do not reach into each other. - A store (NgRx, ComponentStore) only when there is real need: optimistic updates, undo, many actors over the same data, or devtools as a requirement. A store introduced "for consistency" in a five-module app usually becomes the place where every feature is coupled to every other.
6 · The folder tree I would actually create
src/
app/
core/ singletons — no UI, no feature imports
auth/ oidc client, token storage, session facade
http/ api client, interceptors, problem-details mapping
guards/ auth.guard.ts · role-match.guard.ts · unsaved.guard.ts
config/ runtime config loader + InjectionTokens
telemetry/ ErrorHandler, logger, correlation id
shared/ stateless and reusable
ui/ button, table, empty-state, badge, dialog
directives/ clickOutside, autofocus, hasPermission
pipes/ weight, money, timeAgo
forms/ validators, ControlValueAccessor controls
layout/ shell: header, sidenav, breadcrumbs, outlet
features/
dashboard/ routes.ts · state/ · data/ · ui/
shipments/ routes.ts · state/ · data/ · ui/
billing/ routes.ts · state/ · data/ · ui/
reports/ routes.ts · state/ · data/ · ui/
admin/ routes.ts · state/ · data/ · ui/
app.routes.ts root routes — one lazy entry per capability
app.config.ts providers: http, router, interceptors, initializers
assets/config.json runtime configuration, not build-time
environments/ build defaults only, never secrets
Inside a feature the four folders are the same everywhere, so a developer who knows one feature knows all five: routes.ts (entry and guards), data/ (HTTP calls and DTO mapping), state/ (signals or store), ui/ (smart containers and dumb components). Consistency across features is worth more than a perfect internal layout in one of them.
7 · Quality gates that exist before the first feature
- TypeScript strict —
strict: true,noImplicitAny,strictTemplatesintsconfig. Retrofitting strictness into a five-module app costs weeks; adopting it atng newcosts nothing. - Lint with boundaries — ESLint + Prettier, plus the import rule from the table above, plus
no-floating-promises(an unawaited HTTP call is a silent defect). - Bundle budgets in
angular.json: a warning at 500 kB initial and an error at 1 MB. Budgets turn "the app feels slow" into a red build on the pull request that caused it. - Tests in three layers — unit for pipes, validators and pure functions; component tests with a host component for the shared UI; Playwright for the two or three flows that move money.
- CI order — install → lint → typecheck → unit → build → e2e → publish artefact. The build is the artefact that gets promoted; nothing is rebuilt per environment.
8 · Rendering and configuration choices made at setup
SPA by default; SSR plus hydration when first paint or SEO matters, and then the rule that no component touches window, document or localStorage directly — isPlatformBrowser, Renderer2 and injected abstractions instead, or the build starts failing in prerender. Configuration lives in assets/config.json loaded at runtime; secrets never enter the SPA at all, because everything shipped to the browser is public.
9 · When the application outgrows one project
One application is the right answer until roughly five to eight features, or until two teams need independent release cadence. At that point the same boundaries become an Nx workspace with libraries (ui, data-access, one lib per feature) and enforced module tags — not because monorepos are fashionable, but because the dependency rule I wrote on day one is already the shape of the libraries, and moving is mechanical instead of a rewrite.
10 · What actually breaks at five modules
| Symptom | Usual cause | Fix |
|---|---|---|
| Main bundle grows every sprint | A heavy component imported eagerly through a barrel file | Budgets in CI, no barrel re-export of heavy modules, lazy route for the heavy screen |
| Two sessions, two token refreshes | Auth provided in a shared module imported by two lazy features | Singletons only in core/ or providedIn: 'root' |
| Circular imports, build order surprises | Features importing each other's services | Move the contract to core/, expose a facade, emit events |
| Navigation runs twice | A guard returning an observable that emits more than once | first()/take(1), and test the guard in isolation |
| Slow first paint after a deploy | Everything preloaded, or a stale service worker caching old chunks | Role-aware preloading, versioned cache, hard refresh strategy |
11 · The first two weeks, in order
- Days 1–2 — repository, strict TypeScript, ESLint with boundaries, Prettier, CI pipeline, bundle budgets.
- Days 3–4 — shell, layout, router skeleton with five lazy stubs, 404 page, route titles.
- Days 5–6 — authentication (OIDC + PKCE), guards, interceptor chain, error normalisation, session facade.
- Days 7–8 — design tokens and the first shared components: button, table, empty state, form field.
- Days 9–10 — one vertical slice end to end (shipments): route, data layer, state, screens, tests, e2e.
That order matters because each step makes the next one cheaper: the shell gives every feature a place to live, authentication removes the excuse to hardcode a user, and one finished vertical slice becomes the template the other four copy.
core/ and what would you refuse to put there? · How do you test that the dependency rule still holds?
Manuela Cortés Granados · Technical evaluation questions