Skip to content

Angular Application Architecture

Most Angular applications are not slow or buggy — they are hard to change. A feature touches nine directories, a service is imported by forty components, and nobody can say what would break if it changed.

Architecture is the set of decisions that determine whether that happens. Almost all of them are cheap now and expensive later, which is why they are worth making deliberately rather than by accretion.

Angular’s style guide is unusually specific here, and following it removes a category of bikeshedding.

Everything UI lives in src. TypeScript, HTML and styles. Configuration and scripts live outside it. This keeps the root consistent between projects and separates UI code from everything else.

Bootstrap in src/main.ts. Always that name — it is the entry point, and every reader knows to look there.

Group closely related files together. A component’s TypeScript, template and styles in one directory. Unit tests live beside the code they test — not in a separate tests tree.

Organise by feature area, not by type. This is the rule most codebases get wrong:

src/
├─ orders/
│ ├─ order-list/
│ ├─ order-detail/
│ ├─ order-api-client.ts
│ └─ orders.routes.ts
├─ customers/
│ ├─ customer-dashboard/
│ └─ customer-api-client.ts
└─ shared/

Not:

src/
├─ components/
├─ services/
├─ directives/
└─ models/

The style guide says explicitly: avoid creating subdirectories based on the type of code in them — no components, directives, services directories. The reason is what happens when you work: a change to “orders” touches one directory in the first layout and four in the second. Type-based grouping optimises for finding all the services, which nobody needs to do; feature grouping optimises for changing a feature, which is the whole job.

Split directories as they grow. Too many files in one directory becomes hard to navigate; add sub-directories.

One concept per file. Usually one component, directive or service. More than one is acceptable when the classes are small and tie together as a single concept. When in doubt, smaller files.

Rule Example
Hyphens in file names UserProfile → user-profile.ts
Tests share the name with .spec user-profile.spec.ts
File name matches the identifier order-api-client.ts
Component files share a base name user-profile.ts / .html / .css
Multiple style files describe their scope user-profile-settings.css

And the negative rule that matters most: avoid generic file names like helpers.ts, utils.ts or common.ts. A file that can hold anything eventually holds everything, and nothing in it can be found or safely changed.

The most useful component-level distinction, whatever you call it.

Presentational components take inputs, emit outputs, and render. No injected services, no data fetching, no routing. Reusable, trivially testable, and easy to reason about.

Smart components inject services, fetch data, own state, and compose presentational components.

// Presentational: knows nothing about where data comes from.
@Component({
selector: 'order-row',
template: `
<span>{{ order().customer }}</span>
<span>{{ order().total | currency }}</span>
<button (click)="cancelOrder.emit(order().id)">Cancel</button>
`,
})
export class OrderRow {
readonly order = input.required<Order>();
readonly cancelOrder = output<string>();
}
// Smart: owns the data and the decisions.
@Component({
selector: 'orders-portal',
imports: [OrderRow],
template: `
@for (order of visible(); track order.id) {
<order-row [order]="order" (cancelOrder)="cancel($event)" />
}
`,
})
export class OrdersPortal {
private readonly api = inject(OrderApiClient);
readonly orders = httpResource<Order[]>(() => '/api/orders');
readonly filter = signal('');
readonly visible = computed(() => /* ... */);
cancel(id: string): void { /* ... */ }
}

Angular’s own guidance points the same way: keep components and directives focused on presentation, and factor anything that makes sense independently of the UI — validation rules, data transformations — into separate functions or classes.

Do not apply the split dogmatically. A screen-level component that fetches and renders is fine; the distinction earns its keep when a presentational piece is reused, or when a smart component grows large enough that the rendering is worth isolating.

A few style-guide rules with more value than their size suggests:

Group Angular-specific properties before methods — injected dependencies, inputs, outputs, queries — so a reader sees the component’s template API and dependencies immediately.

Use protected for members only the template reads. A component’s public members are its API, reachable through DI and queries. A computed used only by the template is not part of that API:

export class UserProfile {
readonly firstName = input<string>();
readonly lastName = input<string>();
protected readonly fullName = computed(() => `${this.firstName()} ${this.lastName()}`);
}

Use readonly for anything Angular initialises — input, model, output, queries. It prevents overwriting a value Angular set.

Name event handlers for what they do, not for the event: (click)="saveUserData()", not (click)="handleClick()". The template then reads as a description of behaviour.

Keep lifecycle hooks simple. ngOnInit names when code runs, not what it does, so put the logic in well-named methods and call them:

ngOnInit(): void {
this.startLogging();
this.runBackgroundTask();
}

Implement the lifecycle interfaces (OnInit, OnDestroy) so a typo in a hook name is a compile error rather than a method that silently never runs.

Three kinds of service, with different lifetimes and different rules.

API clients — one per resource or bounded context, root-provided, stateless. They know URLs and response shapes so nothing else has to.

State services — own a slice of application state with signals. Expose read-only signals and methods; never a writable signal.

Utility services — formatting, validation, calculation. Often these should be plain functions rather than services at all: a pure function is easier to test, tree-shakable, and needs no injection context.

The provision level is the lifetime decision:

Provided at Lifetime For
@Service() / root The application Stateless collaborators, genuinely global state
Route.providers Created on first use under the route; not destroyed on navigation by default (see Routing) Feature state shared by one feature’s screens; reset it explicitly if it must not survive leaving
Component providers The component instance Per-instance state (a row editor, a wizard)

Root-scoped mutable state is the default that causes the most trouble: it survives navigation, bleeds between users of a long-lived tab, and needs an explicit reset somebody will forget to call. See Dependency Injection in Angular.

The rule that keeps a codebase from becoming a graph: dependencies point inward and downward, never sideways between features.

routes → feature → shared → core
  • A feature may depend on shared and core.
  • A feature must not import from another feature. Two features that need each other’s data both depend on something below them.
  • shared must not depend on any feature. The moment it does, it is not shared.

When two features genuinely need to communicate, the options are: move the shared concept down into core, communicate through the router (the URL as the interface), or have the parent route coordinate them. What you must not do is import orders/order-api-client from inside customers/ — that is the first edge of the graph, and once one exists the rest follow.

The other rule with teeth: shared is not a dumping ground. A SharedModule exporting forty things was the NgModule-era version; a shared/index.ts barrel is the standalone version of the same mistake. Import from specific files, and if something is used by exactly one feature, it lives in that feature.

Four places, in order of preference:

  1. In the component, as a signal. Most state is local and should stay local.
  2. In the URL, as route or query params. Anything a user would share, bookmark, or expect back after a refresh — filters, sorting, pagination, the selected record.
  3. In a feature-scoped service, provided by Route.providers. State several components in one feature share.
  4. In a root service, only for genuinely application-wide state: the authenticated user, a theme, feature flags.

Most “we need state management” conversations are really about level 3, and a signal-based service usually answers it. See State Management in Angular.

Module federation splits an application across independently deployed builds. It solves a real problem — several teams releasing on independent schedules against one user-facing application — and it costs real complexity: shared-dependency version alignment, cross-application routing, contract versioning, and a debugging story that spans repositories.

The honest test: is your constraint organisational or technical? If several teams need to deploy independently, micro frontends address that directly. If a single team wants smaller bundles, lazy-loaded routes give you most of the benefit with none of the cost.

This repository has dedicated Micro Frontend material covering the implementation.

Anti-pattern Cost
Type-based directories (components/, services/) Every feature change touches four directories
SharedModule or a shared/index.ts barrel Everything depends on everything; bundlers over-include
utils.ts / helpers.ts / common.ts Becomes a junk drawer nobody can safely change
Cross-feature imports Coupling graph; a change anywhere breaks anywhere
All state in root services State survives navigation; leaks between users in a tab
Business logic in components Untestable without a fixture; unreusable
UI state duplicated in a service and the URL Two sources of truth; they drift
Public writable signals on services Anyone can mutate shared state from anywhere
Components fetching data directly with HttpClient URLs and response shapes spread through the UI
Deep component trees for their own sake Prop drilling and indirection with no benefit
Micro frontends for a single team Deployment and dependency complexity, no organisational payoff
src/
├─ main.ts
├─ app/
│ ├─ app.ts
│ ├─ app.config.ts ← ApplicationConfig: provideRouter, provideHttpClient, tokens
│ └─ app.routes.ts
├─ core/ ← application-wide, no feature knowledge
│ ├─ auth/
│ ├─ error-handling/
│ └─ http-interceptors/
├─ shared/ ← reusable, no feature or domain knowledge
│ ├─ ui/ ← presentational components
│ └─ formatting/ ← plain functions
├─ orders/
│ ├─ orders.routes.ts
│ ├─ order-api-client.ts
│ ├─ orders-feature-state.ts ← provided by Route.providers
│ ├─ order-list/
│ └─ order-detail/
└─ customers/
└─ …

The properties that make it work: a feature is one directory; shared and core know nothing about features; features know nothing about each other; each feature’s routes are a lazy-loading boundary and a provider scope; and tests sit beside the code they test.

“Why organise by feature rather than by type?” Because work happens per feature. Adding a field to orders touches one directory under feature organisation and four under type organisation, and the four-directory version makes every change look larger than it is in review. Type-based grouping optimises for “find all the services”, which nobody actually needs to do. Angular’s style guide states it directly: avoid subdirectories based on the type of code in them. It also makes lazy-loading boundaries obvious, because a feature directory is already the unit you would split.

“Two features need each other’s data. How do you handle it?” Not with a direct import — that is the first edge in a dependency graph that will not stay at one edge. The options in order: move the shared concept down into core or shared so both features depend on it rather than on each other; communicate through the router, using the URL as the interface; or let a parent route coordinate them. If neither feature is willing to give up the concept, that usually means the feature boundary is wrong and they are one feature.

“Where does application state belong?” As locally as it can. Component signals for most of it. The URL for anything a user would share, bookmark or expect back after a refresh — filters, sorting, pagination, the open record. A feature-scoped service provided by Route.providers for state shared within a feature — visible only to that feature, but not destroyed on navigation by default, so reset it explicitly where it must not survive leaving. A root service only for genuinely application-wide state. The failure mode is putting everything in root services, where it survives navigation, bleeds between users in a long-lived tab, and needs an explicit reset somebody forgets.

“When are micro frontends the right call?” When the constraint is organisational — several teams that need to deploy independently against one user-facing application. They solve a release-coordination problem, and they cost shared-dependency alignment, cross-application routing, contract versioning, and debugging that spans repositories. If a single team just wants smaller bundles, lazy-loaded routes give most of the benefit at almost none of the cost, and I would push hard on that before splitting a build.

“What makes a SharedModule bad, and does standalone fix it?” It creates an all-to-all dependency: every importer gets everything, bundlers over-include, and nothing can be changed safely because everything might use it. Standalone components fix it structurally, since each component lists what it uses — but only if you delete the shared module rather than converting it into a barrel of re-exports, which reintroduces exactly the same coupling with different syntax. The test is whether removing an item from shared requires knowing who uses it; if it does, you have a module again.

“A colleague wants every component split into smart and presentational. Push back or agree?” Partly. The distinction is genuinely useful where a presentational piece is reused, or where a container has grown enough that isolating the rendering helps. Applied to every component it produces a layer of pass-through wrappers that add indirection and no testability — a screen-level component that fetches and renders is fine. I would frame the actual rule as Angular’s: keep components focused on presentation and factor out anything that makes sense independently of the UI. That is the goal; smart-and-presentational is one way to reach it, not the goal itself.