Sub topic 10
Layering inside and across features
This chapter assumes you can write standalone Angular components and inject services. It also assumes you have seen a feature folder with its own route file, and that you know what a barrel file and a path alias are. The earlier chapters on feature folders, core and shared code, barrels and aliases cover those.
Why a feature folder needs inner structure
A feature folder keeps related code together, but it does not stop that code from tangling. In a feature that grows past a dozen files, a presentational button can end up calling HttpClient. A date helper can import a store. A store can import a routed component. Each shortcut is small. Together they make it impossible to reuse or test any piece alone.
Layering fixes this with one rule: every file has a type, and each type may import only certain other types. The same four types work inside a feature and across features.
The four layer types
| Layer | Contains | May import |
|---|---|---|
| feature | Routed components and containers that wire a screen together | ui, data-access, util |
| ui | Presentational components, directives and pipes that get everything through inputs and outputs | ui, util |
| data-access | Stores, API services, models and mappers | data-access, util |
| util | Pure functions, constants and types with no Angular or HTTP dependency | util |
Two points about this table.
- Imports only flow downward. A feature may use anything below it, and nothing below it may use a feature.
- ui and data-access never import each other. A ui component that needs data receives it from the feature component above it.
One feature, four layers
Inside the orders folder, the layers become subfolders:
src/app/orders/
feature/
order-list.component.ts
order-detail.component.ts
ui/
order-row.component.ts
data-access/
orders.store.ts
order.model.ts
util/
format-money.ts
orders.routes.ts
index.tsThe feature/ and data-access/ names match the route file and store shown earlier in this tutorial. Now fill in the layers from the bottom up. The util layer is a pure function:
// orders/util/format-money.ts
export function formatMoney(cents: number, currency = 'USD'): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(cents / 100);
}The model lives in data-access:
// orders/data-access/order.model.ts
export interface Order {
id: string;
customer: string;
totalCents: number;
}The ui component takes plain values. It does not import Order, because that type lives in data-access and ui may not depend on it:
// orders/ui/order-row.component.ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { formatMoney } from '../util/format-money';
@Component({
selector: 'app-order-row',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<span>{{ customer() }}</span>
<span>{{ total() }}</span>
<button type="button" (click)="selected.emit(id())">Open</button>
`,
})
export class OrderRowComponent {
readonly id = input.required<string>();
readonly customer = input.required<string>();
readonly totalCents = input.required<number>();
readonly selected = output<string>();
protected readonly total = computed(() => formatMoney(this.totalCents()));
}The feature component sits on top. It is the only place that knows about the store, the ui component and the router at once:
// orders/feature/order-list.component.ts
import { Component, OnInit, inject } from '@angular/core';
import { Router } from '@angular/router';
import { OrdersStore } from '../data-access/orders.store';
import { OrderRowComponent } from '../ui/order-row.component';
@Component({
selector: 'app-order-list',
imports: [OrderRowComponent],
template: `
<h2>Orders ({{ store.count() }})</h2>
@for (order of store.orders(); track order.id) {
<app-order-row
[id]="order.id"
[customer]="order.customer"
[totalCents]="order.totalCents"
(selected)="open($event)"
/>
}
`,
})
export class OrderListComponent implements OnInit {
protected readonly store = inject(OrdersStore);
private readonly router = inject(Router);
ngOnInit(): void {
this.store.load();
}
protected open(id: string): void {
this.router.navigate(['/orders', id]);
}
}This is the payoff of the layering. OrderRowComponent can be tested with three inputs and no providers. OrdersStore can be tested without any component. formatMoney can be tested with no Angular at all.
The dependency direction
Util is the base because it knows nothing about the rest. The feature layer is the top because it knows the most. Putting a component in the right layer comes down to asking what it needs to know.
- If it needs the router or a store, it is a feature.
- If it only needs inputs, it is ui.
- If it needs
HttpClientor holds state, it is data-access. - If it needs nothing from Angular, it is util.
Layers across features
The same four types apply between features. Each feature has its own feature, ui, data-access and util folders, and its barrel exposes only what other code is allowed to import. Three rules keep features independent:
- One feature never imports another feature's internal files. It imports through the other feature's barrel or path alias, such as
@app/orders. - Code that two features both need moves down a level, to a shared area. Shared ui components go in
shared/ui, and shared helpers go inshared/util. - Shared code never imports from a feature. If
shared/uiimportsOrder, it has become a hidden part of the orders feature.
This is where the core and shared folders from the earlier chapter fit in. They are layers of their own. shared/ui and shared/util follow the same import rules as the ui and util folders inside a feature.
Scoping by feature as well as by type
Type layers answer "what kind of code is this?". They do not answer "which feature does it belong to?". A customers ui component should not import an orders ui component. Tooling that supports it lets you put a second tag on each folder or library, a scope tag such as scope:orders. A rule can then say that a library may depend on its own scope and on scope:shared, and on nothing else. The next chapter covers how to enforce this.
Where shared domain data goes
Sometimes two features both need the same server data, for example the orders feature needs a customer's name. Do not import customers/data-access/... directly. Pick one of these options instead:
- Export a small, deliberate API from the
customersbarrel, such as a lookup function or a read-only signal. - Pass the value in from a parent feature or the route, so the orders feature never imports
customersat all. - Move the shared model and API service into a shared data-access area that both features may depend on.
The first two keep the features loosely coupled. The third is simpler but grows into a catch-all if used for everything. A later chapter compares these options in detail.
Common errors
- A ui component that fetches data. Adding
inject(HttpClient)to a ui component moves it into data-access territory. Move the call up to the feature component or store, and pass the result down as an input. - A util file that imports Angular. If a "util" needs
inject(), it is a service, so it belongs in data-access or feature. - A model placed in ui. Models used by both ui and data-access cannot live in either one. Either place the shared type in util, or give ui plain inputs as above. Plain inputs are usually better, because ui then does not depend on your domain model.
- Features calling each other's stores. If
ordersinjectsCustomersStore, you have a runtime dependency that the folder structure hides. Route it through a barrel API or a parent. - One layer per file. Over-layering is also a risk. A feature with two files does not need four subfolders. Add a layer folder when it has several files that clearly belong together.
Check your understanding
Exercise
In the orders feature, OrderRowComponent in ui/ needs to show the customer's name and a formatted total. A teammate proposes importing Order from data-access/order.model.ts for its input type and injecting OrdersStore to read the current order. Which layer rules does this break, and how do you fix it?
Show answer
It breaks the rule that ui may import only ui and util. Importing Order makes ui depend on data-access, and injecting OrdersStore adds a second dependency on data-access that also hides the component's real inputs. To fix it, give the component plain inputs (id, customer, totalCents) and an output for the click. Let the feature component read from OrdersStore and pass the values down. The component then needs no providers in tests.
Exercise
A formatMoney helper is needed in both the orders feature and the customers feature. Where should it live, and which import paths are allowed?
Show answer
Move it to shared/util, since two features need it and it has no Angular or domain dependencies. Both features may import it from the shared util area. Neither feature should import it from the other's util folder, and shared/util must not import anything from a feature.