Welcome to the Angular Style Guide
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.
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.
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.
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.
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.
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.
Table of contents
- Single responsibility
- Coding conventions
- App structure and Angular modules
- Data services
- Lifecycle hooks
Apply the Single Responsibility Principle (SPR) to all components, services, and other symbols. This helps make the app cleaner, easier to read and maintain, and more testable.
Rule of One
Do define one thing, such as a service or component, per file.
Consider limiting files to 400 lines of code.
Why? One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.
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.
Why? A single component can be the default export for its file which facilitates lazy loading with the router.
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.
It is a better practice to redistribute the component and its supporting classes into their own, dedicated files.
As the app grows, this rule becomes even more important.Back to top
Do define small functions
Consider limiting to no more than 75 lines.
Why? Small functions are easier to test, especially when they do one thing and serve one purpose.
Why? Small functions promote reuse.
Why? Small functions are easier to read.
Why? Small functions are easier to maintain.
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.
Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.
General Naming Guidelines
Do use consistent names for all symbols.
Do follow a pattern that describes the symbol's feature then its type. The recommended pattern is
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? The naming conventions should simply help find desited code faster and make it easier to understand.
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.
Separate file names with dots and dashes
Do use dashes to separate words in the descriptive name.
Do use dots to separate the descriptive name from the type.
Do use consistent type names for all components following a pattern that describes the component's feature then its type. A recommended pattern is
Do use conventional type names including
Invent additional type names if you must but take care not to create too many.
Why? Type names provide a consistent way to quickly identify what is in the file.
Why? Type names make it easy to find a specific file type using an editor or IDE's fuzzy search techniques.
Why? Unabbreviated type names such as
.service are descriptive and unambiguous.
Abbreviations such as
.serv can be confusing.
Why? Type names provide pattern matching for any automated tasks.
Symbols and file names
Do use consistent names for all assets named after what they represent.
Do use upper camel case for class names.
Do match the name of the symbol to the name of the file.
Do append the symbol name with the conventional suffix (such as
Service) for a thing of that type.
Do give the filename the conventional suffix (such as
.service.ts) for a file of that type.
Why? Consistent conventions make it easy to quickly identify and reference assets of different types.
|Symbol Name||File Name|
Do use consistent names for all services named after their feature.
Do suffix a service class name with Service.
For example, something that gets data or heroes
should be called a
DataService or a
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
Decide if this exception is agreeable in your project.
As always, strive for consistency.
Why? Provides a consistent way to quickly identify and reference services.
Why? Clear service names such as
Logger do not require a suffix.
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.
|Symbol Name||File Name|
Do put bootstrapping and platform logic for the app in a file named
Do include error handling in the bootstrapping logic.
Avoid putting app logic in the
main.ts. Instead, consider placing it in a component or service.
Why? Follows a consistent convention for the startup logic of an app.
Why? Follows a familiar convention from other technology platforms.
Do Use lower camel case for naming the selectors of directives.
Why? Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.
Why? The Angular HTML parser is case sensitive and will recognize lower camel case.
Custom prefix for components
Do use a hyphenated, lowercase element selector value (e.g.
Do use a custom prefix for a component selector.
For example, the prefix
toh represents from Tour of Heroes and the prefix
admin represents an admin feature area.
Do use a prefix that identifies the feature area or the app itself.
Why? Prevents element name collisions with components in other apps and with native HTML elements.
Why? Makes it easier to promote and share the component in other apps.
Why? Components are easy to identify in the DOM.
Custom prefix for directives
Do use a custom prefix for the selector of directives (e.g, the prefix
toh from Tour of Heroes).
Do spell non-element selectors in lower camel case unless the selector is meant to match a native HTML attribute.
Why? Prevents name collisions.
Why? Directives are easily identified.
Do use consistent names for all pipes, named after their feature.
Why? Provides a consistent way to quickly identify and reference pipes.
|Symbol Name||File Name|
Unit test file names
Do name test specification files the same as the component they test.
Do name test specification files with a suffix of
Why? Provides a consistent way to quickly identify tests.
Why? Provides pattern matching for karma or other test runners.
|Symbol Name||File Name|
End-to-End (E2E) test file names
Do name end-to-end test specification files after the feature they test with a suffix of
Why? Provides a consistent way to quickly identify end-to-end tests.
Why? Provides pattern matching for test runners and build automation.
|Symbol Name||File Name|
End to End Tests
Angular NgModule names
Do append the symbol name with the suffix
Do give the file name the
Do name the module after the feature and folder it resides in.
Why? Provides a consistent way to quickly identify and reference modules.
Why? Upper camel case is conventional for identifying objects that can be instantiated using a constructor.
Why? Easily identifies the module as the root of the same named feature.
Do suffix a RoutingModule class name with
Do end the filename of a RoutingModule with
RoutingModule is a module dedicated exclusively to configuring the Angular router.
A consistent class and file name convention make these modules easy to spot and verify.
|Symbol Name||File Name|
Have consistent set of coding, naming, and whitespace conventions.
Do use upper camel case when naming classes.
Why? Follows conventional thinking for class names.
Why? Classes can be instantiated and construct an instance. By convention, upper camel case indicates a constructable asset.
Do declare variables with
const if their values should not change during the application lifetime.
Why? Conveys to readers that the value is invariant.
Why? TypeScript helps enforce that intent by requiring immediate initialization and by preventing subsequent re-assignment.
const variables in lower camel case.
Why? Lower camel case variable names (
heroRoutes) are easier to read and understand
than the traditional UPPER_SNAKE_CASE names (
Why? The tradition of naming constants in UPPER_SNAKE_CASE reflects
an era before the modern IDEs that quickly reveal the
TypeScript itself prevents accidental reassignment.
Do tolerate existing
const variables that are spelled in UPPER_SNAKE_CASE.
Why? The tradition of UPPER_SNAKE_CASE remains popular and pervasive, especially in third party modules. It is rarely worth the effort to change them at the risk of breaking existing code and documentation.
Do name an interface using upper camel case.
Consider naming an interface without an
Consider using a class instead of an interface.
Why? TypeScript guidelines
Why? A class alone is less code than a class-plus-interface.
Why? A class can act as an interface (use
implements instead of
Why? An interface-class can be a provider lookup token in Angular dependency injection.
Properties and methods
Do use lower camel case to name properties and methods.
Avoid prefixing private properties and methods with an underscore.
Why? Follows conventional thinking for properties and methods.
Why? TypeScript tooling makes it easy to identify private vs public properties and methods.
Import line spacing
Consider leaving one empty line between third party imports and application imports.
Consider listing import lines alphabetized by the module.
Consider listing destructured imported symbols alphabetically.
Why? The empty line separates your stuff from their stuff.
Why? Alphabetizing makes it easier to read and locate symbols.
Application structure and Angular modules
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
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
You didn't write them and you don't want them cluttering
Use the naming conventions for files in this guide.
Do structure the app such that you can
Locate code quickly,
Identify the code at a glance,
Flattest structure you can, and
Try to be DRY.
Do define the structure to follow these four basic guidelines, listed in order of importance.
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?
Do make locating code intuitive, simple and fast.
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.
Do name the file such that you instantly know what it contains and represents.
Do be descriptive with file names and keep the contents of the file to exactly one component.
Avoid files with multiple components, multiple services, or a mixture.
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.
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.
Do keep a flat folder structure as long as possible.
Consider creating sub-folders when a folder reaches seven or more files.
Consider configuring the IDE to hide distracting, irrelevant files such as generated
Why? No one wants to search for a file through seven levels of folders. A flat structure is easy to scan.
On the other hand, psychologists believe that humans start to struggle when the number of adjacent interesting things exceeds nine. So when a folder has ten or more files, it may be time to create subfolders.
Base your decision on your comfort level. Use a flatter structure until there is an obvious value to creating a new folder.
T-DRY (Try to be DRY)
Do be DRY (Don't Repeat Yourself)
Avoid being so DRY that you sacrifice readability.
Why? Being DRY is important, but not crucial if it sacrifices the other elements of LIFT.
That's why it's called T-DRY.
For example, it's redundant to name a component,
hero-view.component.html because a component is obviously a view.
But if something is not obvious or departs from a convention, then spell it out.
Overall structural guidelines
Do start small but keep in mind where the app is heading down the road.
Do have a near term view of implementation and a long term vision.
Do put all of the app's code in a folder named
Consider creating a folder for a component when it has multiple accompanying files (
Why? Helps keep the app structure small and easy to maintain in the early stages, while being easy to evolve as the app grows.
Why? Components often have four files (e.g.
*.spec.ts) and can clutter a folder quickly.
Here is a compliant folder and file structure:
While components in dedicated folders are widely preferred, another option for small apps is to keep components flat (not in a dedicated folder). This adds up to four files to the existing folder, but also reduces the folder nesting. Whatever you choose, be consistent.
Do create folders named for the feature area they represent.
Why? A developer can locate the code, identify what each file represents at a glance, the structure is as flat as it can be, and there are no repetitive or redundant names.
Why? The LIFT guidelines are all covered.
Why? Helps reduce the app from becoming cluttered through organizing the content and keeping them aligned with the LIFT guidelines.
Why? When there are a lot of files (e.g. 10+), locating them is easier with a consistent folder structure and more difficult in a flat structure.
Do create an Angular module for each feature area.
Why? Angular modules make it easy to lazy load routable features.
Why? Angular modules make it easier to isolate, test, and re-use features.
App root module
Do create an Angular module in the app's root folder (e.g., in
Why? Every app requires at least one root Angular module.
Consider naming the root module
Why? Makes it easier to locate and identify the root module.
Do create an Angular module for all distinct features in an application (e.g.
Do place the feature module in the same named folder as the feature area (.e.g
Do name the feature module file reflecting the name of the feature area and folder (e.g.
Do name the feature module symbol reflecting the name of the feature area, folder, and file (e.g.
Why? A feature module can expose or hide its implementation from other modules.
Why? A feature module identifies distinct sets of related components that comprise the feature area.
Why? A feature module can easily be routed to both eagerly and lazily.
Why? A feature module defines clear boundaries between specific functionality and other application features.
Why? A feature module helps clarify and make it easier to assign development responsibilities to different teams.
Why? A feature module can easily be isolated for testing.
Shared feature module
Do create a feature module named
SharedModule in a
shared folder (e.g.
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.
Consider using the name SharedModule, when the contents of a shared module are referenced across the entire application.
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.
Do import all modules required by the assets in the
SharedModule will contain components, directives and pipes that may need features from another common module (e.g.
Do declare all components, directives, and pipes in the
Do export all symbols from the
SharedModule that other feature modules need to use.
SharedModule exists to make commonly used components, directives and pipes available for use in the templates of components in many other modules.
Avoid specifying app-wide singleton providers in a
SharedModule. Intentional singletons are OK. Take care.
Why? A lazy loaded feature module that imports that shared module will make its own copy of the service and likely have undesireable results.
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.
Core feature module
Consider collecting numerous, auxiliary, single-use classes inside a core module to simplify the apparent structure of a feature module.
Consider calling the application-wide core module,
CoreModule into the root
AppModule reduces its complexity
and emphasizes its role as orchestrator of the application as a whole.
Do create a feature module named
CoreModule in a
core folder (e.g.
Do put a singleton service whose instance wil be shared throughout the application in the
Do import all modules required by the assets in the
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.
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.
Do gather application-wide, single use components in the
Import it once (in the
AppModule) when the app starts and never import it anywhere else. (e.g.
Why? Real world apps can have several single-use components (e.g., spinners, message toasts, and modal dialogs) that appear only in the
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.
Avoid importing the
CoreModule anywhere except in the
Why? A lazily loaded feature module that directly imports the
CoreModule will make its own copy of services and likely have undesireable results.
Why? An eagerly loaded feature module already has access to the
AppModule's injector, and thus the
Do export all symbols from the
CoreModule that the
AppModule will import and make available for other feature modules to use.
CoreModule exists to make commonly used singleton services available for use in the many other modules.
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.
AppModule is a little smaller because many app/root classes have moved to other modules.
AppModule is stable because you will add future components and providers to other modules, not this one.
AppModule delegates to imported modules rather than doing work.
AppModule is focused on its main task, orchestrating the app as a whole.
Prevent re-import of the core module
Only the root
AppModule should import the
Do guard against reimporting of
CoreModule and fail fast by adding guard logic.
Why? Guards against reimporting of the
Why? Guards against creating multiple instances of assets intended to be singletons.
Lazy Loaded folders
A distinct application feature or workflow may be lazy loaded or loaded on demand rather than when the application starts.
Do put the contents of lazy loaded features in a lazy loaded folder. A typical lazy loaded folder contains a routing component, its child components, and their related assets and modules.
Why? The folder makes it easy to identify and isolate the feature content.
Never directly import lazy loaded folders
Avoid allowing modules in sibling and parent folders to directly import a module in a lazy loaded feature.
Why? Directly importing and using a module will load it immediately when the intention is to load it on demand.
Component selector names
Do use dashed-case or kebab-case for naming the element selectors of components.
Why? Keeps the element names consistent with the specification for Custom Elements.
Components as elements
Do give components an element selector, as opposed to attribute or class selectors.
Why? components have templates containing HTML and optional Angular template syntax. They display content. Developers place components on the page as they would native HTML elements and WebComponents.
Why? It is easier to recognize that a symbol is a component by looking at the template's html.
Extract templates and styles to their own files
Do extract templates and styles into a separate file, when more than 3 lines.
Do name the template file
[component-name].component.html, where [component-name] is the component name.
Do name the style file
[component-name].component.css, where [component-name] is the component name.
Do specify component-relative URLs, prefixed with
./, and add
moduleId: module.id to the component metadata.
Why? Large, inline templates and styles obscure the component's purpose and implementation, reducing readability and maintainability.
Why? In most editors, syntax hints and code snippets aren't available when developing inline templates and styles. The Angular TypeScript Language Service (forthcoming) promises to overcome this deficiency for HTML templates in those editors that support it; it won't help with CSS styles.
Why? A component relative URL requires no change when you move the component files, as long as the files stay together.
Why? The JIT compiler requires the
moduleId for relative URLs; the AOT compiler,
which doesn't need it, safely ignores this property.
./ prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix.
Decorate input and output properties
Do use the
@Output class decorators instead of the
outputs properties of the
@Output() on the same line as the property it decorates.
Why? It is easier and more readable to identify which properties in a class are inputs or outputs.
Why? If you ever need to rename the property or event name associated with
@Output, you can modify it in a single place.
Why? The metadata declaration attached to the directive is shorter and thus more readable.
Why? Placing the decorator on the same line usually makes for shorter code and still easily identifies the property as an input or output. Put it on the line above when doing so is clearly more readable.
Avoid aliasing inputs and outputs
Avoid input and output aliases except when it serves an important purpose.
Why? Two names for the same property (one private, one public) is inherently confusing.
Why? You should use an alias when the directive name is also an input property, and the directive name doesn't describe the property.
Do place properties up top followed by methods.
Do place private members after public members, alphabetized.
Why? Placing members in a consistent sequence makes it easy to read and helps instantly identify which members of the component serve which purpose.
Delegate complex component logic to services
Do limit logic in a component to only that required for the view. All other logic should be delegated to services.
Do move reusable logic to services and keep components simple and focused on their intended purpose.
Why? Logic may be reused by multiple components when placed within a service and exposed via a function.
Why? Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked.
Why? Removes dependencies and hides implementation details from the component.
Why? Keeps the component slim, trim, and focused.
Don't prefix output properties
Do name events without the prefix
Do name event handler methods with the prefix
on followed by the event name.
Why? This is consistent with built-in events such as button clicks.
Why? Angular allows for an alternative syntax
on-*. If the event itself was prefixed with
on this would result in an
on-onEvent binding expression.
Put presentation logic in the component class
Do put presentation logic in the component class, and not in the template.
Why? Logic will be contained in one place (the component class) instead of being spread in two places.
Why? Keeping the component's presentation logic in the class instead of the template improves testability, maintainability, and reusability.
DirectivesBack to top
Use directives to enhance an element
Do use attribute directives when you have presentation logic without a template.
Why? Attributes directives don't have an associated template.
Why? An element may have more than one attribute directive applied.
HostListener/HostBinding decorators versus host metadata
Consider preferring the
@HostBinding to the
host property of the
Do be consistent in your choice.
Why? The property associated with
@HostBinding or the method associated with
can be modified only in a single place - in the directive's class.
If you use the
host metadata property, you must modify both the property declaration inside the controller,
and the metadata associated with the directive.
Compare with the less preferred
host metadata alternative.
host metadata is only one term to remember and doesn't require extra ES imports.
Services are singletons
Do use services as singletons within the same injector. Use them for sharing data and functionality.
Why? Services are ideal for sharing methods across a feature area or an app.
Why? Services are ideal for sharing stateful in-memory data.
Do create services with a single responsibility that is encapsulated by its context.
Do create a new service once the service begins to exceed that singular purpose.
Why? When a service has multiple responsibilities, it becomes difficult to test.
Why? When a service has multiple responsibilities, every component or service that injects it now carries the weight of them all.
Providing a service
Do provide services to the Angular injector at the top-most component where they will be shared.
Why? The Angular injector is hierarchical.
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.
Why? This is ideal when a service is sharing methods or state.
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.
Use the @Injectable() class decorator
Do use the
@Injectable class decorator instead of the
@Inject parameter decorator when using types as tokens for the dependencies of a service.
Why? The Angular Dependency Injection (DI) mechanism resolves a service's own dependencies based on the declared types of that service's constructor parameters.
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.
Talk to the server through a service
Do refactor logic for making data operations and interacting with data to a service.
Do make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.
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.
Why? This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.
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.
Use Lifecycle hooks to tap into important events exposed by Angular.Back to top
Implement lifecycle hook interfaces
Do implement the lifecycle hook interfaces.
Why? Lifecycle interfaces prescribe typed method signatures. use those signatures to flag spelling and syntax mistakes.
Useful tools and tips for Angular.Back to top
Do use codelyzer to follow this guide.
Consider adjusting the rules in codelyzer to suit your needs.
File templates and snippets
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.