Sub topic 15
Organizing code as the application grows
This chapter assumes you can create a workspace with ng new, you know what ng generate produces, and you have read the route configuration file (app.routes.ts). It covers how to arrange folders once the application has more than a handful of components. You will see the common layouts, how the CLI places generated files, how to keep boundaries clean, and the mistakes that make a growing codebase hard to change.
Why folder structure matters
The CLI does not enforce a structure. It creates src/app with a few files and places generated files where you tell it to. The structure that works for ten files stops working at a hundred, because finding, reviewing and deleting code becomes slow.
Good organization has three goals:
- A developer can find everything about one feature in one place.
- Deleting a feature means deleting a folder, not hunting through the tree.
- Dependencies point in one direction, so a change in one area does not break unrelated areas.
Two ways to group files
Grouping by type
A layout grouped by type puts all components together, all services together, and so on.
src/app/
components/
services/
models/
pipes/This looks tidy at first. It fails as the app grows. One feature, such as products, ends up spread over four folders, and each folder gets hundreds of unrelated files.
Grouping by feature
A layout grouped by feature puts everything for one area of the product in one folder.
src/app/
products/
product-list/
product-detail/
product.service.ts
product.model.ts
products.routes.ts
orders/
order-list/
order.service.ts
orders.routes.ts
shared/
core/
app.config.ts
app.routes.ts
app.component.tsAngular's own style guidance favors this approach. A folder for a feature holds its components, services, models and routes. The rest of the application only needs to know the feature's route file.
Using ng generate to place files
The path you give to ng generate decides the folder. The CLI creates missing folders and resolves the path from src/app.
ng generate component products/product-list
ng generate component products/product-detail
ng generate service products/product
ng generate pipe shared/pipes/currency-shortEach command creates files next to each other. The first creates src/app/products/product-list/ with the component class, template, stylesheet and spec file. The service command creates product.service.ts directly in src/app/products/, because services have no folder of their own by default.
Two details help in daily use:
- Run
ng generatefrom the workspace root, or from any folder insidesrc/app. When you run it from insidesrc/app/products, the CLI treats the current directory as the base path, so you can writeng generate component product-edit. - Add
--dry-run(or-d) to preview the files without writing them. Use it when you are unsure where a file will land.
ng generate component products/product-edit --dry-runSplitting routes by feature
Each feature should own its routes. The root file only points to them, and the feature's routes load on demand.
// src/app/products/products.routes.ts
import { Routes } from '@angular/router';
export const PRODUCT_ROUTES: Routes = [
{
path: '',
loadComponent: () =>
import('./product-list/product-list.component').then(
(m) => m.ProductListComponent
),
},
{
path: ':id',
loadComponent: () =>
import('./product-detail/product-detail.component').then(
(m) => m.ProductDetailComponent
),
},
];// src/app/app.routes.ts
import { Routes } from '@angular/router';
export const routes: Routes = [
{
path: 'products',
loadChildren: () =>
import('./products/products.routes').then((m) => m.PRODUCT_ROUTES),
},
{
path: 'orders',
loadChildren: () =>
import('./orders/orders.routes').then((m) => m.ORDER_ROUTES),
},
{ path: '', redirectTo: 'products', pathMatch: 'full' },
];The dynamic import() calls tell the build to put each feature in its own JavaScript chunk. The browser downloads a feature's code only when the user visits its route. Feature folders therefore also act as the unit of lazy loading.
Component file names depend on your CLI version. Newer versions generate product-list.ts and a class named ProductList. Adjust the import paths and class names to match what your CLI produced.
The core, shared and feature split
Most growing applications settle on three kinds of folders.
| Folder | Holds | Rule |
|---|---|---|
| `features` or feature folders (`products/`, `orders/`) | Screens, feature services, feature models | May import from `core` and `shared`. Should not import from other features. |
| `shared/` | Reusable dumb pieces: buttons, pipes, directives, formatting helpers | Has no knowledge of any feature. No application-wide state. |
| `core/` | Singletons used once: auth service, HTTP interceptors, app-wide layout | Provided once at the root. Not imported by `shared`. |
The key rule is the direction of imports. Features depend on shared and core. Neither shared nor core depends on a feature. When two features need the same code, move it down into shared or core instead of importing sideways.
The diagram below shows the allowed direction.
Services and where they are provided
Where a service lives in the folder tree is separate from where it is provided. A service marked providedIn: 'root' is a single instance for the whole application, whichever folder holds it.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ProductService {
// one instance for the whole app, but the file lives in products/
}Keep a service inside its feature folder when only that feature uses it. If another feature needs it, either move it to core or expose a small, deliberate public API from the feature.
Public entry points with barrel files
A barrel file is an index.ts that re-exports selected items from a folder.
// src/app/products/index.ts
export { PRODUCT_ROUTES } from './products.routes';
export type { Product } from './product.model';Other code imports from ./products and cannot reach into internals by accident. Use barrels sparingly. Large barrels can create circular imports and can hamper tree shaking, so export only what the outside world needs.
Path aliases
Deep relative imports such as ../../../shared/ui/button are fragile. The paths option in tsconfig.json creates short aliases.
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@core/*": ["src/app/core/*"],
"@shared/*": ["src/app/shared/*"]
}
}
}You can then write import { Button } from '@shared/ui/button'. The CLI build reads these paths from the TypeScript configuration, so no separate bundler setup is needed. Keep the alias list short. A handful of aliases for the top-level folders is enough.
Common mistakes
- Putting everything in
shared. If a component is used by only one feature, it belongs in that feature. Asharedfolder that holds the whole app has no meaning. - Features importing each other. This creates hidden coupling and circular imports. Lift the common piece to
sharedorcore. - Generating into the wrong folder. Running
ng generate component listfrom the workspace root puts files atsrc/app/list/. Check with--dry-run. - Eager imports of lazy features. If
app.routes.tsimports a feature's component with a staticimportfor any reason, the build bundles it into the main chunk and lazy loading is lost. - Reorganizing too early. Start with a flat
src/app. Create a feature folder when a second file for the same feature appears.
A practical growth path
- Start with the generated files in
src/app. - When you add a second screen for the same area, create a feature folder and move the files into it.
- Add a
routesfile to the feature and switch toloadChildrenin the root routes. - When two features share code, create
shared/. Put application-wide singletons incore/. - When the same code must be used by several applications, consider a library in a multi-project workspace, which a later chapter covers.
Exercise
Your orders feature needs a formatPrice function that already exists inside the products feature folder. Importing it directly from products would work. Why is it better not to, and what should you do instead?
Show answer
Importing from another feature couples the two features, so a change or removal in products can break orders, and it can lead to circular imports. Move formatPrice into shared/ (for example shared/utils/format-price.ts), then import it from there in both features. Features depend on shared, never sideways on each other.
Exercise
You run ng generate component cart-summary from the workspace root, but you wanted the component in src/app/orders/cart-summary/. What command produces the right result, and how can you check the result before files are written?
Show answer
Run ng generate component orders/cart-summary. Add --dry-run first (ng generate component orders/cart-summary --dry-run) to list the files the CLI would create without writing them.