Angular Directory Structure: Optimized for MVVM and Component Splitting
Introduction
I adopted the MVVM (Model-View-ViewModel) architecture and organized components using the Container/Presentational pattern in my latest Angular project. This article provides a guide to a scalable directory structure to enhance maintainability and clarity.
Prerequisites
Before diving into the directory structure, review the Angular coding style guide. This guide provides comprehensive advice on various Angular development topics, including directory structure and coding best practices.
Directory Structure
Below is the directory structure I implemented in my Angular project, split into three primary directories: core
, features
, and shared
.
src/
|-- app/
| |-- core/
| | |-- constants/
| | |-- decorators/
| | |-- guards/
| | |-- interceptors/
| | |-- interfaces/
| | | `-- api/
| | |-- models/
| | |-- resolvers/
| | |-- services/
| | | `-- api/
| | `-- validators/
| |-- features/
| | |-- auth/
| | | |-- password-reset/
| | | |-- sign-in/
| | | |-- sign-up/
| | | |-- verify/
| | | |-- auth.module.ts
| | | |-- auth.service.ts
| | | `-- auth-routing.module.ts
| | `-- .../
| |-- shared/
| | |-- components/
| | |-- directives/
| | | |-- attribute/
| | | `-- structural/
| | |-- forms/
| | | |-- input/
| | | |-- select/
| | | `-- .../
| | |-- pipes/
| | `-- services/
| |-- app.component.ts
| |-- app.module.ts
| `-- app-routing.module.ts
|-- assets/
|-- environments/
|-- styles/
|-- tests/
|-- theme/
`-- global.scss
Directory Breakdown
-
core
Contains application-wide functionality, including constants, guards, interceptors, models, and services. These are accessible by thefeatures
directory but should never reference features or shared components. -
features
Each feature module resides here. These modules may referencecore
orshared
but must remain isolated from the rest of the application to maintain modularity. -
shared
Contains feature-wide reusable parts like directives, forms, pipes, and services. These are available tofeatures
but must avoid referencing them.
Why Use Subdirectories
While the Angular coding style guide advises keeping directories flat, you should consider subdirectories when a folder exceeds seven files. This enhances clarity and organization in large projects.
Consider creating sub-folders when a folder reaches seven or more files. – Angular coding style guide
Conclusion
Designing a well-organized directory structure is crucial for building scalable Angular applications. By adopting the MVVM architecture and leveraging the Container/Presentational pattern, you can enhance both maintainability and team collaboration.
Happy Coding! 🚀