Sub topic 1
Why group code by feature, not by file type
Prerequisites
This chapter assumes you can read and write TypeScript, and that you know basic Angular: components, templates, and dependency injection. You should also know what the Angular Router does and be able to run the Angular CLI and npm. Later chapters build on the ideas introduced here. This chapter explains the reasoning and gives a first look at the layout. It does not configure routes, providers, or lint rules yet.
Two ways to organize the same code
Every Angular app has to decide where files live. There are two common answers.
The first groups by file type. Folders are named after what the code is: components/, services/, models/, pipes/, guards/. This is what many early tutorials show, and it is easy to start with.
The second groups by feature. Folders are named after what the code is for: orders/, customers/, billing/. Each folder holds the components, services, models, and routes that one part of the business needs.
Here is the same small app in both layouts.
# By file type
src/app/
components/
order-list.component.ts
order-detail.component.ts
customer-list.component.ts
services/
orders.service.ts
customers.service.ts
models/
order.model.ts
customer.model.ts
# By feature
src/app/
orders/
order-list.component.ts
order-detail.component.ts
orders.service.ts
order.model.ts
customers/
customer-list.component.ts
customers.service.ts
customer.model.tsWith three components and two services, both layouts feel fine. The difference shows up as the app grows.
Where file-type layouts break down
A change request usually sounds like "let users filter orders by status". That touches the order list, the orders service, the order model, and perhaps a pipe or a guard. In a file-type layout, those files sit in four or five different folders. You open each folder, scroll past files from unrelated features, and keep the connection between them in your head.
Four problems follow from this.
- Related files are far apart. The files that change together are not near each other. Reviewing a pull request means jumping across the tree.
- Folders grow without limit. After a year,
services/can hold 80 files. The folder name tells you nothing about which ones matter for your task. - Everything looks shared. Any file can import any other file, and nothing marks which imports are intended. Tangled dependencies form quietly, such as the customer list importing a private helper from the order service.
- Nothing can be loaded or removed on its own. Since the code for one feature is scattered, you cannot easily load it on demand, hand it to a team, or delete it.
The underlying issue is that file type is a weak boundary. A service is a technical role. It says nothing about which part of the product the code serves, so it cannot tell you what may depend on what.
What a feature gives you
A feature is a slice of the product that users and teams talk about: "orders", "customer profile", "checkout". Grouping by feature gives each slice a boundary. A boundary is useful in several concrete ways.
- Locality. Most changes stay inside one folder. Reading, testing, and reviewing a change take less jumping.
- Ownership. A team can own
orders/. Reviewers know who to ask. - Lazy loading. A feature that lives in one place can be loaded by the router only when the user navigates to it. This reduces the initial bundle.
- Encapsulation. A feature can decide what it exposes and keep the rest private.
- Deletability. Removing a feature means removing a folder and a route entry, not hunting through six directories.
A useful test is the deletion test. Ask what you would do if the product team said to drop the feature. If the answer is "delete one folder and one line in the routes file", the boundary is good.
A first look at how the pieces connect
The rest of this tutorial turns the feature folder into a real boundary, using Angular's own mechanisms. The following example shows the first step. The app-level routes file does nothing but map a URL prefix to a feature, and it loads each feature lazily.
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDERS_ROUTES),
},
{
path: 'customers',
loadChildren: () =>
import('./customers/customers.routes').then((m) => m.CUSTOMERS_ROUTES),
},
];Each import() call is a dynamic import. The bundler turns it into a separate file that the browser downloads the first time the user visits /orders or /customers. The app shell needs to know only the URL prefix and the name of one exported routes constant. It does not need to know which components or services the feature contains.
Later chapters cover the other tools in the same way. Route-level providers keep a feature's services out of the root injector. A barrel file lists the symbols other code may import. Path aliases give those imports stable names. Lint rules turn all of this from convention into a build failure.
Trade-offs and edge cases
Grouping by feature is not free, and it does not remove the need for judgment.
Deciding what a feature is. Features should follow the business, not the screens. A feature named dashboard-widgets is a technical grouping in disguise. A feature named billing that holds invoices, payment methods, and receipts is a better fit if one team and one set of rules govern them. If two folders always change together, they are probably one feature. If one folder has two unrelated reasons to change, it is probably two.
Shared code. Some code serves several features: a button, a date formatter, an HTTP interceptor. Putting it in a feature would force other features to import across the boundary. Such code belongs in shared or core folders, covered in a later chapter. Be careful here, because shared/ can turn into a new dumping ground. Move code there only when at least two features really use it. Moving it earlier guesses at a need that may never arrive.
Folders do not enforce anything. A feature folder is a convention. Nothing stops customers/ from importing ../orders/orders.service. Without an enforced rule, a feature layout slowly decays into the same tangle as the file-type layout, only with different folder names. This is why the later chapters on barrels and lint rules matter.
Small apps. An app with five components and one service gains little from feature folders. The structure pays off when several people work in parallel, when features have their own routes and state, or when the bundle size matters. Starting with feature folders from the beginning costs little, though, and avoids a later migration.
Mixed layouts inside a feature. Within a feature folder, you may still sort files by role, for example feature/, ui/, and data-access/. That is a different thing from a top-level services/ folder. The top level answers "which part of the product", and the inner level answers "what role does this file play in it".
| Question | By file type | By feature |
|---|---|---|
| Where do I find code for one task? | Spread over many folders | Mostly one folder |
| What decides a file's location? | Its technical role | The product area it serves |
| Can the router load it on demand? | Awkward, files are scattered | Natural, one routes entry |
| Can I delete it as a unit? | Rarely | Usually |
| Are boundaries enforced by default? | No | No, needs barrels and lint rules |
How this connects to the next chapters
The plan from here follows the order in which a feature gains structure. Standalone components become the unit of composition. Feature folders get a standard layout, with core and shared code defined next to them. The router then loads features lazily, and route-level providers and signals keep their state inside them. After that, barrels, path aliases, and lint rules mark the edges and defend them. The final chapters cover communication between features, testing, workspaces, and migration of an existing app.
Exercise
A team has components/, services/, and models/ folders at the top of its app. A request arrives to add a "cancel order" action. Name two practical problems the team will meet with this layout, and describe the first step toward a feature-based layout.
Show answer
Possible problems: the files for "cancel order" are spread across three or more folders, so the change is harder to find, review, and test as one unit; and nothing marks which imports between folders are intended, so the new code may depend on private details of unrelated services. The first step is to create an orders/ folder and move the order-related components, service, and model into it. Then register the feature in the app routes with a lazy loadChildren entry so the app shell only knows the URL prefix and the routes constant.
Exercise
Why is a feature folder alone not enough to keep features independent, and what will later chapters add to fix it?
Show answer
A folder is only a convention. Any file can still import any other file by relative path, so features can become tangled again. Later chapters add a barrel file that defines the public API, path aliases that give imports a stable name, and lint rules that fail the build when code crosses a boundary it should not.