Looking for an opinionated guide to Angular syntax, conventions, and application structure?
Step right in!
This style guide presents our preferred conventions and, as importantly, explains why.
## Style vocabulary
Each guideline describes either a good or bad practice, and all have a consistent presentation.
The wording of each guideline indicates how strong the recommendation is.
~~~ {.s-rule.do}
**Do** is one that should always be followed.
_Always_ might be a bit too strong of a word.
Guidelines that literally should always be followed are extremely rare.
On the other hand, you need a really unusual case for breaking a *Do* guideline.
~~~
~~~ {.s-rule.consider}
**Consider** guidelines should generally be followed.
If you fully understand the meaning behind the guideline and have a good reason to deviate, then do so. Please strive to be consistent.
~~~
~~~ {.s-rule.avoid}
**Avoid** indicates something you should almost never do. Code examples to *avoid* have an unmistakeable red header.
~~~
## File structure conventions
Some code examples display a file that has one or more similarly named companion files.
For example, `hero.component.ts` and `hero.component.html`.
The guideline will use the shortcut `hero.component.ts|html|css|spec` to represent those various files. Using this shortcut makes this guide's file structures easier to read and more terse.
This helps make the app cleaner, easier to read and maintain, and more testable.
### <a id="01-01"></a>_Rule of One_
#### <a href="#01-01">Style 01-01</a>
~~~ {.s-rule.do}
**Do** define one thing, such as a service or component, per file.
~~~
~~~ {.s-rule.consider}
**Consider** limiting files to 400 lines of code.
~~~
<divclass='s-why'>
**Why?** One component per file makes it far easier to read, maintain, and avoid
collisions with teams in source control.
</div>
<divclass='s-why'>
**Why?** One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** A single component can be the default export for its file which facilitates lazy loading with the router.
</div>
The key is to make the code more reusable, easier to read, and less mistake prone.
The following *negative* example defines the `AppComponent`, bootstraps the app, defines the `Hero` model object, and loads heroes from the server ... all in the same file. *Don't do this*.
As the app grows, this rule becomes even more important.
<ahref="#toc">Back to top</a>
### <a id="01-02"></a>Small functions
#### <a href="#01-02">Style 01-02</a>
~~~ {.s-rule.do}
**Do** define small functions
~~~
~~~ {.s-rule.consider}
**Consider** limiting to no more than 75 lines.
~~~
<divclass='s-why'>
**Why?** Small functions are easier to test, especially when they do one thing and serve one purpose.
</div>
<divclass='s-why'>
**Why?** Small functions promote reuse.
</div>
<divclass='s-why'>
**Why?** Small functions are easier to read.
</div>
<divclass='s-why'>
**Why?** Small functions are easier to maintain.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.
</div>
<ahref="#toc">Back to top</a>
## Naming
Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.
### <a id="02-01"></a>General Naming Guidelines
#### <a href="#02-01">Style 02-01</a>
~~~ {.s-rule.do}
**Do** use consistent names for all symbols.
~~~
~~~ {.s-rule.do}
**Do** follow a pattern that describes the symbol's feature then its type. The recommended pattern is `feature.type.ts`.
~~~
<divclass='s-why'>
**Why?** Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency.
**Why?** Names of folders and files should clearly convey their intent. For example, `app/heroes/hero-list.component.ts` may contain a component that manages a list of heroes.
</div>
<ahref="#toc">Back to top</a>
### <a id="02-02"></a>Separate file names with dots and dashes
#### <a href="#02-02">Style 02-02</a>
~~~ {.s-rule.do}
**Do** use dashes to separate words in the descriptive name.
~~~
~~~ {.s-rule.do}
**Do** use dots to separate the descriptive name from the type.
~~~
~~~ {.s-rule.do}
**Do** use consistent type names for all components following a pattern that describes the component's feature then its type. A recommended pattern is `feature.type.ts`.
~~~
~~~ {.s-rule.do}
**Do** use conventional type names including `.service`, `.component`, `.pipe`, `.module`, and `.directive`.
Invent additional type names if you must but take care not to create too many.
~~~
<divclass='s-why'>
**Why?** Type names provide a consistent way to quickly identify what is in the file.
</div>
<divclass='s-why'>
**Why?** Type names make it easy to find a specific file type using an editor or IDE's fuzzy search techniques.
</div>
<divclass='s-why'>
**Why?** Unabbreviated type names such as `.service` are descriptive and unambiguous.
Abbreviations such as `.srv`, `.svc`, and `.serv` can be confusing.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** Type names provide pattern matching for any automated tasks.
</div>
<ahref="#toc">Back to top</a>
### <a id="02-03"></a>Symbols and file names
#### <a href="#02-03">Style 02-03</a>
~~~ {.s-rule.do}
**Do** use consistent names for all assets named after what they represent.
~~~
~~~ {.s-rule.do}
**Do** use upper camel case for class names.
~~~
~~~ {.s-rule.do}
**Do** match the name of the symbol to the name of the file.
~~~
~~~ {.s-rule.do}
**Do** append the symbol name with the conventional suffix (such as `Component`,
`Directive`, `Module`, `Pipe`, or `Service`) for a thing of that type.
~~~
~~~ {.s-rule.do}
**Do** give the filename the conventional suffix (such as `.component.ts`, `.directive.ts`,
`.module.ts`, `.pipe.ts`, or `.service.ts`) for a file of that type.
~~~
<divclass='s-why'>
**Why?** Consistent conventions make it easy to quickly identify
and reference assets of different types.
</div>
<tablewidth="100%">
<colwidth="50%">
</col>
<colwidth="50%">
</col>
<tr>
<th>
Symbol Name
</th>
<th>
File Name
</th>
</tr>
<trstyle=top>
<td>
<code-example>
@Component({ ... })
export class AppComponent { }
</code-example>
</td>
<td>
app.component.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Component({ ... })
export class HeroesComponent { }
</code-example>
</td>
<td>
heroes.component.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Component({ ... })
export class HeroListComponent { }
</code-example>
</td>
<td>
hero-list.component.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Component({ ... })
export class HeroDetailComponent { }
</code-example>
</td>
<td>
hero-detail.component.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Directive({ ... })
export class ValidationDirective { }
</code-example>
</td>
<td>
validation.directive.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@NgModule({ ... })
export class AppModule
</code-example>
</td>
<td>
app.module.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Pipe({ name: 'initCaps' })
export class InitCapsPipe implements PipeTransform { }
</code-example>
</td>
<td>
init-caps.pipe.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Injectable()
export class UserProfileService { }
</code-example>
</td>
<td>
user-profile.service.ts
</td>
</tr>
</table>
<ahref="#toc">Back to top</a>
### <a id="02-04"></a>Service names
#### <a href="#02-04">Style 02-04</a>
~~~ {.s-rule.do}
**Do** use consistent names for all services named after their feature.
~~~
~~~ {.s-rule.do}
**Do** suffix a service class name with Service.
For example, something that gets data or heroes
should be called a `DataService` or a `HeroService`.
A few terms are unambiguously services. They typically
indicate agency by ending in "er". You may prefer to name
a service that logs messages `Logger` rather than `LoggerService`.
Decide if this exception is agreeable in your project.
As always, strive for consistency.
~~~
<divclass='s-why'>
**Why?** Provides a consistent way to quickly identify and reference services.
</div>
<divclass='s-why'>
**Why?** Clear service names such as `Logger` do not require a suffix.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** Service names such as `Credit` are nouns and require a suffix and should be named with a suffix when it is not obvious if it is a service or something else.
</div>
<tablewidth="100%">
<colwidth="50%">
</col>
<colwidth="50%">
</col>
<tr>
<th>
Symbol Name
</th>
<th>
File Name
</th>
</tr>
<trstyle=top>
<td>
<code-example>
@Injectable()
export class HeroDataService { }
</code-example>
</td>
<td>
hero-data.service.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Injectable()
export class CreditService { }
</code-example>
</td>
<td>
credit.service.ts
</td>
</tr>
<trstyle=top>
<td>
<code-example>
@Injectable()
export class Logger { }
</code-example>
</td>
<td>
logger.service.ts
</td>
</tr>
</table>
<ahref="#toc">Back to top</a>
### <a id="02-05"></a>Bootstrapping
#### <a href="#02-05">Style 02-05</a>
~~~ {.s-rule.do}
**Do** put bootstrapping and platform logic for the app in a file named `main.ts`.
~~~
~~~ {.s-rule.do}
**Do** include error handling in the bootstrapping logic.
~~~
~~~ {.s-rule.avoid}
**Avoid** putting app logic in the `main.ts`. Instead, consider placing it in a component or service.
~~~
<divclass='s-why'>
**Why?** Follows a consistent convention for the startup logic of an app.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** Follows a familiar convention from other technology platforms.
</div>
{@example 'style-guide/ts/src/02-05/main.ts'}
<ahref="#toc">Back to top</a>
### <a id="02-06"></a>Directive selectors
#### <a href="#02-06">Style 02-06</a>
~~~ {.s-rule.do}
**Do** Use lower camel case for naming the selectors of directives.
~~~
<divclass='s-why'>
**Why?** Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** The Angular HTML parser is case sensitive and will recognize lower camel case.
</div>
<ahref="#toc">Back to top</a>
### <a id="02-07"></a>Custom prefix for components
#### <a href="#02-07">Style 02-07</a>
~~~ {.s-rule.do}
**Do** use a hyphenated, lowercase element selector value (e.g. `admin-users`).
~~~
~~~ {.s-rule.do}
**Do** use a custom prefix for a component selector.
For example, the prefix `toh` represents from **T**our **o**f **H**eroes and the prefix `admin` represents an admin feature area.
~~~
~~~ {.s-rule.do}
**Do** use a prefix that identifies the feature area or the app itself.
~~~
<divclass='s-why'>
**Why?** Prevents element name collisions with components in other apps and with native HTML elements.
</div>
<divclass='s-why'>
**Why?** Makes it easier to promote and share the component in other apps.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** Components are easy to identify in the DOM.
Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road.
All of the app's code goes in a folder named `src`.
All feature areas are in their own folder, with their own Angular module.
All content is one asset per file. Each component, service, and pipe is in its own file.
All third party vendor scripts are stored in another folder and not in the `src` folder.
You didn't write them and you don't want them cluttering `src`.
Use the naming conventions for files in this guide.
<ahref="#toc">Back to top</a>
### <a id="04-01"></a>_LIFT_
#### <a href="#04-01">Style 04-01</a>
~~~ {.s-rule.do}
**Do** structure the app such that you can `L`ocate code quickly,
`I`dentify the code at a glance,
keep the `F`lattest structure you can, and
`T`ry to be DRY.
~~~
~~~ {.s-rule.do}
**Do** define the structure to follow these four basic guidelines, listed in order of importance.
~~~
<divclass='s-why'class='s-why-last'>
**Why?** LIFT Provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly.
To confirm your intuition about a particular structure, ask:
_can I quickly open and start work in all of the related files for this feature_?
</div>
<ahref="#toc">Back to top</a>
### <a id="04-02"></a>Locate
#### <a href="#04-02">Style 04-02</a>
~~~ {.s-rule.do}
**Do** make locating code intuitive, simple and fast.
~~~
<divclass='s-why'class='s-why-last'>
**Why?**
To work efficiently you must be able to find files quickly,
especially when you do not know (or do not remember) the file _names_.
Keeping related files near each other in an intuitive location saves time.
A descriptive folder structure makes a world of difference to you and the people who come after you.
</div>
<ahref="#toc">Back to top</a>
### <a id="04-03"></a>Identify
#### <a href="#04-03">Style 04-03</a>
~~~ {.s-rule.do}
**Do** name the file such that you instantly know what it contains and represents.
~~~
~~~ {.s-rule.do}
**Do** be descriptive with file names and keep the contents of the file to exactly one component.
~~~
~~~ {.s-rule.avoid}
**Avoid** files with multiple components, multiple services, or a mixture.
~~~
<divclass='s-why'class='s-why-last'>
**Why?** Spend less time hunting and pecking for code, and become more efficient.
Longer file names are far better than _short-but-obscure_ abbreviated names.
</div>
It may be advantageous to deviate from the _one-thing-per-file_ rule when
you have a set of small, closely-related features that are better discovered and understood
in a single file than as multiple files. Be wary of this loophole.
<ahref="#toc">Back to top</a>
### <a id="04-04"></a>Flat
#### <a href="#04-04">Style 04-04</a>
~~~ {.s-rule.do}
**Do** keep a flat folder structure as long as possible.
~~~
~~~ {.s-rule.consider}
**Consider** creating sub-folders when a folder reaches seven or more files.
~~~
~~~ {.s-rule.consider}
**Consider** configuring the IDE to hide distracting, irrelevant files such as generated `.js` and `.js.map` files.
~~~
<divclass='s-why'class='s-why-last'>
**Why?** No one wants to search for a file through seven levels of folders.
**Do** create an Angular module for all distinct features in an application (e.g. `Heroes` feature).
~~~
~~~ {.s-rule.do}
**Do** place the feature module in the same named folder as the feature area (.e.g `app/heroes`).
~~~
~~~ {.s-rule.do}
**Do** name the feature module file reflecting the name of the feature area and folder (e.g. `app/heroes/heroes.module.ts`)
~~~
~~~ {.s-rule.do}
**Do** name the feature module symbol reflecting the name of the feature area, folder, and file (e.g. `app/heroes/heroes.module.ts` defines `HeroesModule`)
~~~
<divclass='s-why'>
**Why?** A feature module can expose or hide its implementation from other modules.
</div>
<divclass='s-why'>
**Why?** A feature module identifies distinct sets of related components that comprise the feature area.
</div>
<divclass='s-why'>
**Why?** A feature module can easily be routed to both eagerly and lazily.
</div>
<divclass='s-why'>
**Why?** A feature module defines clear boundaries between specific functionality and other application features.
</div>
<divclass='s-why'>
**Why?** A feature module helps clarify and make it easier to assign development responsibilities to different teams.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** A feature module can easily be isolated for testing.
</div>
<ahref="#toc">Back to top</a>
### <a id="04-10"></a>Shared feature module
#### <a href="#04-10">Style 04-10</a>
~~~ {.s-rule.do}
**Do** create a feature module named `SharedModule` in a `shared` folder (e.g. `app/shared/shared.module.ts` defines `SharedModule`).
~~~
~~~ {.s-rule.do}
**Do** declare components, directives, and pipes in a shared module when those
items will be re-used and referenced by the components declared in other feature modules.
~~~
~~~ {.s-rule.consider}
**Consider** using the name SharedModule, when the contents of a shared
module are referenced across the entire application.
~~~
~~~ {.s-rule.do}
**Do** not provide services in shared modules. Services are usually
singletons that are provided once for the entire application or
in a particular feature module.
~~~
~~~ {.s-rule.do}
**Do** import all modules required by the assets in the `SharedModule` (e.g. `CommonModule` and `FormsModule`).
~~~
<divclass='s-why'>
**Why?**`SharedModule` will contain components, directives and pipes that may need features from another common module (e.g. `ngFor` in `CommonModule`).
</div>
~~~ {.s-rule.do}
**Do** declare all components, directives, and pipes in the `SharedModule`.
~~~
~~~ {.s-rule.do}
**Do** export all symbols from the `SharedModule` that other feature modules need to use.
~~~
<divclass='s-why'>
**Why?**`SharedModule` exists to make commonly used components, directives and pipes available for use in the templates of components in many other modules.
</div>
~~~ {.s-rule.avoid}
**Avoid** specifying app-wide singleton providers in a `SharedModule`. Intentional singletons are OK. Take care.
~~~
<divclass='s-why'>
**Why?** A lazy loaded feature module that imports that shared module will make its own copy of the service and likely have undesireable results.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** You don't want each module to have its own separate instance of singleton services.
Yet there is a real danger of that happening if the `SharedModule` provides a service.
**Consider** collecting numerous, auxiliary, single-use classes inside a core module
to simplify the apparent structure of a feature module.
~~~
~~~ {.s-rule.consider}
**Consider** calling the application-wide core module, `CoreModule`.
Importing `CoreModule` into the root `AppModule` reduces its complexity
and emphasizes its role as orchestrator of the application as a whole.
~~~
~~~ {.s-rule.do}
**Do** create a feature module named `CoreModule` in a `core` folder (e.g. `app/core/core.module.ts` defines `CoreModule`).
~~~
~~~ {.s-rule.do}
**Do** put a singleton service whose instance wil be shared throughout the application in the `CoreModule` (e.g. `ExceptionService` and `LoggerService`).
~~~
~~~ {.s-rule.do}
**Do** import all modules required by the assets in the `CoreModule` (e.g. `CommonModule` and `FormsModule`).
~~~
<divclass='s-why'>
**Why?**`CoreModule` provides one or more singleton services. Angular registers the providers with the app root injector, making a singleton instance of each service available to any component that needs them, whether that component is eagerly or lazily loaded.
</div>
<divclass='s-why'>
**Why?**`CoreModule` will contain singleton services. When a lazy loaded module imports these, it will get a new instance and not the intended app-wide singleton.
</div>
~~~ {.s-rule.do}
**Do** gather application-wide, single use components in the `CoreModule`.
Import it once (in the `AppModule`) when the app starts and never import it anywhere else. (e.g. `NavComponent` and `SpinnerComponent`).
~~~
<divclass='s-why'>
**Why?** Real world apps can have several single-use components (e.g., spinners, message toasts, and modal dialogs) that appear only in the `AppComponent` template.
They are not imported elsewhere so they're not shared in that sense.
Yet they're too big and messy to leave loose in the root folder.
</div>
~~~ {.s-rule.avoid}
**Avoid** importing the `CoreModule` anywhere except in the `AppModule`.
~~~
<divclass='s-why'>
**Why?** A lazily loaded feature module that directly imports the `CoreModule` will make its own copy of services and likely have undesireable results.
</div>
<divclass='s-why'>
**Why?** An eagerly loaded feature module already has access to the `AppModule`'s injector, and thus the `CoreModule`'s services.
</div>
~~~ {.s-rule.do}
**Do** export all symbols from the `CoreModule` that the `AppModule` will import and make available for other feature modules to use.
~~~
<divclass='s-why'>
**Why?**`CoreModule` exists to make commonly used singleton services available for use in the many other modules.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** You want the entire app to use the one, singleton instance.
You don't want each module to have its own separate instance of singleton services.
Yet there is a real danger of that happening accidentally if the `CoreModule` provides a service.
**Why?** Angular allows for an [alternative syntax](guide/template-syntax) `on-*`. If the event itself was prefixed with `on` this would result in an `on-onEvent` binding expression.
**Do** create services with a single responsibility that is encapsulated by its context.
~~~
~~~ {.s-rule.do}
**Do** create a new service once the service begins to exceed that singular purpose.
~~~
<divclass='s-why'>
**Why?** When a service has multiple responsibilities, it becomes difficult to test.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** When a service has multiple responsibilities, every component or service that injects it now carries the weight of them all.
</div>
<ahref="#toc">Back to top</a>
### <a id="07-03"></a>Providing a service
#### <a href="#07-03">Style 07-03</a>
~~~ {.s-rule.do}
**Do** provide services to the Angular injector at the top-most component where they will be shared.
~~~
<divclass='s-why'>
**Why?** The Angular injector is hierarchical.
</div>
<divclass='s-why'>
**Why?** When providing the service to a top level component,
that instance is shared and available to all child components of that top level component.
</div>
<divclass='s-why'>
**Why?** This is ideal when a service is sharing methods or state.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance.
### <a id="07-04"></a>Use the @Injectable() class decorator
#### <a href="#07-04">Style 07-04</a>
~~~ {.s-rule.do}
**Do** use the `@Injectable` class decorator instead of the `@Inject` parameter decorator when using types as tokens for the dependencies of a service.
~~~
<divclass='s-why'>
**Why?** The Angular Dependency Injection (DI) mechanism resolves a service's own
dependencies based on the declared types of that service's constructor parameters.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** When a service accepts only dependencies associated with type tokens, the `@Injectable()` syntax is much less verbose compared to using `@Inject()` on each individual constructor parameter.
### <a id="08-01"></a>Talk to the server through a service
#### <a href="#08-01">Style 08-01</a>
~~~ {.s-rule.do}
**Do** refactor logic for making data operations and interacting with data to a service.
~~~
~~~ {.s-rule.do}
**Do** make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.
~~~
<divclass='s-why'>
**Why?** The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view.
</div>
<divclass='s-why'>
**Why?** This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.
</div>
<divclass='s-why'class='s-why-last'>
**Why?** The details of data management, such as headers, HTTP methods,
caching, error handling, and retry logic, are irrelevant to components
and other data consumers.
A data service encapsulates these details. It's easier to evolve these
details inside the service without affecting its consumers. And it's
easier to test the consumers with mock service implementations.
</div>
<ahref="#toc">Back to top</a>
## Lifecycle hooks
Use Lifecycle hooks to tap into important events exposed by Angular.
**Do** use [codelyzer](https://www.npmjs.com/package/codelyzer) to follow this guide.
~~~
~~~ {.s-rule.consider}
**Consider** adjusting the rules in codelyzer to suit your needs.
~~~
<ahref="#toc">Back to top</a>
### <a id="A-02"></a>File templates and snippets
#### <a href="#A-02">Style A-02</a>
~~~ {.s-rule.do}
**Do** use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs.
~~~
~~~ {.s-rule.consider}
**Consider** using [snippets](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) for [Visual Studio Code](https://code.visualstudio.com/) that follow these styles and guidelines.
**Consider** using [snippets](https://atom.io/packages/angular-2-typescript-snippets) for [Atom](https://atom.io/) that follow these styles and guidelines.
**Consider** using [snippets](https://github.com/orizens/sublime-angular2-snippets) for [Sublime Text](http://www.sublimetext.com/) that follow these styles and guidelines.
**Consider** using [snippets](https://github.com/mhartington/vim-angular2-snippets) for [Vim](http://www.vim.org/) that follow these styles and guidelines.