{ "id": "guide/styleguide", "title": "Angular coding style guide", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Angular coding style guidelink

\n

Looking for an opinionated guide to Angular syntax, conventions, and application structure?\nStep right in!\nThis style guide presents preferred conventions and, as importantly, explains why.

\n\n

Style vocabularylink

\n

Each guideline describes either a good or bad practice, and all have a consistent presentation.

\n

The wording of each guideline indicates how strong the recommendation is.

\n
\n

Do is one that should always be followed.\nAlways might be a bit too strong of a word.\nGuidelines that literally should always be followed are extremely rare.\nOn the other hand, you need a really unusual case for breaking a Do guideline.

\n
\n
\n

Consider guidelines should generally be followed.\nIf you fully understand the meaning behind the guideline and have a good reason to deviate, then do so. Please strive to be consistent.

\n
\n
\n

Avoid indicates something you should almost never do. Code examples to avoid have an unmistakable red header.

\n
\n
\n

Why? gives reasons for following the previous recommendations.

\n
\n

File structure conventionslink

\n

Some code examples display a file that has one or more similarly named companion files.\nFor example, hero.component.ts and hero.component.html.

\n

The guideline uses 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.

\n\n

Single responsibilitylink

\n

Apply the\nsingle responsibility principle (SRP)\nto all components, services, and other symbols.\nThis helps make the app cleaner, easier to read and maintain, and more testable.

\n\n

Rule of Onelink

\n

Style 01-01link

\n
\n

Do define one thing, such as a service or component, per file.

\n
\n
\n

Consider limiting files to 400 lines of code.

\n
\n
\n

Why? One component per file makes it far easier to read, maintain, and avoid\ncollisions with teams in source control.

\n
\n
\n

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.

\n
\n
\n

Why? A single component can be the default export for its file which facilitates lazy loading with the router.

\n
\n

The key is to make the code more reusable, easier to read, and less mistake prone.

\n

The following negative example defines the AppComponent, bootstraps the app,\ndefines the Hero model object, and loads heroes from the server all in the same file.\nDon't do this.

\n\n/* avoid */\nimport { Component, NgModule, OnInit } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\ninterface Hero {\n id: number;\n name: string;\n}\n\n@Component({\n selector: 'app-root',\n template: `\n <h1>{{title}}</h1>\n <pre>{{heroes | json}}</pre>\n `,\n styleUrls: ['app/app.component.css']\n})\nclass AppComponent implements OnInit {\n title = 'Tour of Heroes';\n\n heroes: Hero[] = [];\n\n ngOnInit() {\n getHeroes().then(heroes => (this.heroes = heroes));\n }\n}\n\n@NgModule({\n imports: [BrowserModule],\n declarations: [AppComponent],\n exports: [AppComponent],\n bootstrap: [AppComponent]\n})\nexport class AppModule {}\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\nconst HEROES: Hero[] = [\n { id: 1, name: 'Bombasto' },\n { id: 2, name: 'Tornado' },\n { id: 3, name: 'Magneta' }\n];\n\nfunction getHeroes(): Promise<Hero[]> {\n return Promise.resolve(HEROES); // TODO: get hero data from the server;\n}\n\n\n\n

It is a better practice to redistribute the component and its\nsupporting classes into their own, dedicated files.

\n\n\n \nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\n\nplatformBrowserDynamic().bootstrapModule(AppModule);\n\n\n\n\n \nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { RouterModule } from '@angular/router';\n\nimport { AppComponent } from './app.component';\nimport { HeroesComponent } from './heroes/heroes.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n ],\n declarations: [\n AppComponent,\n HeroesComponent\n ],\n exports: [ AppComponent ],\n bootstrap: [ AppComponent ]\n})\nexport class AppModule { }\n\n\n\n \nimport { Component } from '@angular/core';\n\nimport { HeroService } from './heroes';\n\n@Component({\n selector: 'toh-app',\n template: `\n <toh-heroes></toh-heroes>\n `,\n styleUrls: ['./app.component.css'],\n providers: [HeroService]\n})\nexport class AppComponent {}\n\n\n\n\n \nimport { Component, OnInit } from '@angular/core';\n\nimport { Hero, HeroService } from './shared';\n\n@Component({\n selector: 'toh-heroes',\n template: `\n <pre>{{heroes | json}}</pre>\n `\n})\nexport class HeroesComponent implements OnInit {\n heroes: Hero[] = [];\n\n constructor(private heroService: HeroService) {}\n\n ngOnInit() {\n this.heroService.getHeroes()\n .then(heroes => this.heroes = heroes);\n }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\n\nimport { HEROES } from './mock-heroes';\n\n@Injectable()\nexport class HeroService {\n getHeroes() {\n return Promise.resolve(HEROES);\n }\n}\n\n\n\n\n \nexport interface Hero {\n id: number;\n name: string;\n}\n\n\n\n\n \nimport { Hero } from './hero.model';\n\nexport const HEROES: Hero[] = [\n { id: 1, name: 'Bombasto' },\n { id: 2, name: 'Tornado' },\n { id: 3, name: 'Magneta' }\n];\n\n\n\n\n\n

As the app grows, this rule becomes even more important.\nBack to top

\n\n

Small functionslink

\n

Style 01-02link

\n
\n

Do define small functions

\n
\n
\n

Consider limiting to no more than 75 lines.

\n
\n
\n

Why? Small functions are easier to test, especially when they do one thing and serve one purpose.

\n
\n
\n

Why? Small functions promote reuse.

\n
\n
\n

Why? Small functions are easier to read.

\n
\n
\n

Why? Small functions are easier to maintain.

\n
\n
\n

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.

\n
\n

Back to top

\n

Naminglink

\n

Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.

\n\n

General Naming Guidelineslink

\n

Style 02-01link

\n
\n

Do use consistent names for all symbols.

\n
\n
\n

Do follow a pattern that describes the symbol's feature then its type. The recommended pattern is feature.type.ts.

\n
\n
\n

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.

\n
\n
\n

Why? The naming conventions should simply help find desired code faster and make it easier to understand.

\n
\n
\n

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.

\n
\n

Back to top

\n\n

Separate file names with dots and dasheslink

\n

Style 02-02link

\n
\n

Do use dashes to separate words in the descriptive name.

\n
\n
\n

Do use dots to separate the descriptive name from the type.

\n
\n
\n

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.

\n
\n
\n

Do use conventional type names including .service, .component, .pipe, .module, and .directive.\nInvent additional type names if you must but take care not to create too many.

\n
\n
\n

Why? Type names provide a consistent way to quickly identify what is in the file.

\n
\n
\n

Why? Type names make it easy to find a specific file type using an editor or IDE's fuzzy search techniques.

\n
\n
\n

Why? Unabbreviated type names such as .service are descriptive and unambiguous.\nAbbreviations such as .srv, .svc, and .serv can be confusing.

\n
\n
\n

Why? Type names provide pattern matching for any automated tasks.

\n
\n

Back to top

\n\n

Symbols and file nameslink

\n

Style 02-03link

\n
\n

Do use consistent names for all assets named after what they represent.

\n
\n
\n

Do use upper camel case for class names.

\n
\n
\n

Do match the name of the symbol to the name of the file.

\n
\n
\n

Do append the symbol name with the conventional suffix (such as Component,\nDirective, Module, Pipe, or Service) for a thing of that type.

\n
\n
\n

Do give the filename the conventional suffix (such as .component.ts, .directive.ts,\n.module.ts, .pipe.ts, or .service.ts) for a file of that type.

\n
\n
\n

Why? Consistent conventions make it easy to quickly identify\nand reference assets of different types.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Symbol Name\n \n File Name\n
\n \n @Component({ ... })\n export class AppComponent { }\n \n \n

app.component.ts

\n
\n \n @Component({ ... })\n export class HeroesComponent { }\n \n \n

heroes.component.ts

\n
\n \n @Component({ ... })\n export class HeroListComponent { }\n \n \n

hero-list.component.ts

\n
\n \n @Component({ ... })\n export class HeroDetailComponent { }\n \n \n

hero-detail.component.ts

\n
\n \n @Directive({ ... })\n export class ValidationDirective { }\n \n \n

validation.directive.ts

\n
\n \n @NgModule({ ... })\n export class AppModule\n \n \n

app.module.ts

\n
\n \n @Pipe({ name: 'initCaps' })\n export class InitCapsPipe implements PipeTransform { }\n \n \n

init-caps.pipe.ts

\n
\n \n @Injectable()\n export class UserProfileService { }\n \n \n

user-profile.service.ts

\n
\n

Back to top

\n\n

Service nameslink

\n

Style 02-04link

\n
\n

Do use consistent names for all services named after their feature.

\n
\n
\n

Do suffix a service class name with Service.\nFor example, something that gets data or heroes\nshould be called a DataService or a HeroService.

\n

A few terms are unambiguously services. They typically\nindicate agency by ending in \"-er\". You may prefer to name\na service that logs messages Logger rather than LoggerService.\nDecide if this exception is agreeable in your project.\nAs always, strive for consistency.

\n
\n
\n

Why? Provides a consistent way to quickly identify and reference services.

\n
\n
\n

Why? Clear service names such as Logger do not require a suffix.

\n
\n
\n

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.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Symbol Name\n \n File Name\n
\n \n @Injectable()\n export class HeroDataService { }\n \n \n

hero-data.service.ts

\n
\n \n @Injectable()\n export class CreditService { }\n \n \n

credit.service.ts

\n
\n \n @Injectable()\n export class Logger { }\n \n \n

logger.service.ts

\n
\n

Back to top

\n\n

Bootstrappinglink

\n

Style 02-05link

\n
\n

Do put bootstrapping and platform logic for the app in a file named main.ts.

\n
\n
\n

Do include error handling in the bootstrapping logic.

\n
\n
\n

Avoid putting app logic in main.ts. Instead, consider placing it in a component or service.

\n
\n
\n

Why? Follows a consistent convention for the startup logic of an app.

\n
\n
\n

Why? Follows a familiar convention from other technology platforms.

\n
\n\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\n\nplatformBrowserDynamic().bootstrapModule(AppModule)\n .then(success => console.log(`Bootstrap success`))\n .catch(err => console.error(err));\n\n\n\n

Back to top

\n\n

Component selectorslink

\n

Style 05-02link

\n
\n

Do use dashed-case or kebab-case for naming the element selectors of components.

\n
\n
\n

Why? Keeps the element names consistent with the specification for Custom Elements.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'tohHeroButton',\n templateUrl: './hero-button.component.html'\n})\nexport class HeroButtonComponent {}\n\n\n\n\n \n@Component({\n selector: 'toh-hero-button',\n templateUrl: './hero-button.component.html'\n})\nexport class HeroButtonComponent {}\n\n\n\n \n<toh-hero-button></toh-hero-button>\n\n\n\n\n\n

Back to top

\n\n

Component custom prefixlink

\n

Style 02-07link

\n
\n

Do use a hyphenated, lowercase element selector value; for example, admin-users.

\n
\n
\n

Do use a custom prefix for a component selector.\nFor example, the prefix toh represents Tour of Heroes and the prefix admin represents an admin feature area.

\n
\n
\n

Do use a prefix that identifies the feature area or the app itself.

\n
\n
\n

Why? Prevents element name collisions with components in other apps and with native HTML elements.

\n
\n
\n

Why? Makes it easier to promote and share the component in other apps.

\n
\n
\n

Why? Components are easy to identify in the DOM.

\n
\n\n/* avoid */\n\n// HeroComponent is in the Tour of Heroes feature\n@Component({\n selector: 'hero'\n})\nexport class HeroComponent {}\n\n\n\n/* avoid */\n\n// UsersComponent is in an Admin feature\n@Component({\n selector: 'users'\n})\nexport class UsersComponent {}\n\n\n\n@Component({\n selector: 'toh-hero'\n})\nexport class HeroComponent {}\n\n\n\n@Component({\n selector: 'admin-users'\n})\nexport class UsersComponent {}\n\n\n

Back to top

\n\n

Directive selectorslink

\n

Style 02-06link

\n
\n

Do Use lower camel case for naming the selectors of directives.

\n
\n
\n

Why? Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.

\n
\n
\n

Why? The Angular HTML parser is case sensitive and recognizes lower camel case.

\n
\n

Back to top

\n\n

Directive custom prefixlink

\n

Style 02-08link

\n
\n

Do use a custom prefix for the selector of directives (e.g, the prefix toh from Tour of Heroes).

\n
\n
\n

Do spell non-element selectors in lower camel case unless the selector is meant to match a native HTML attribute.

\n
\n
\n

Don't prefix a directive name with ng because that prefix is reserved for Angular and using it could cause bugs that are difficult to diagnose.

\n
\n
\n

Why? Prevents name collisions.

\n
\n
\n

Why? Directives are easily identified.

\n
\n\n/* avoid */\n\n@Directive({\n selector: '[validate]'\n})\nexport class ValidateDirective {}\n\n\n\n@Directive({\n selector: '[tohValidate]'\n})\nexport class ValidateDirective {}\n\n\n

Back to top

\n\n

Pipe nameslink

\n

Style 02-09link

\n
\n

Do use consistent names for all pipes, named after their feature.\nThe pipe class name should use UpperCamelCase\n(the general convention for class names),\nand the corresponding name string should use lowerCamelCase.\nThe name string cannot use hyphens (\"dash-case\" or \"kebab-case\").

\n
\n
\n

Why? Provides a consistent way to quickly identify and reference pipes.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Symbol Name\n \n File Name\n
\n \n @Pipe({ name: 'ellipsis' })\n export class EllipsisPipe implements PipeTransform { }\n \n \n

ellipsis.pipe.ts

\n
\n \n @Pipe({ name: 'initCaps' })\n export class InitCapsPipe implements PipeTransform { }\n \n \n

init-caps.pipe.ts

\n
\n

Back to top

\n\n

Unit test file nameslink

\n

Style 02-10link

\n
\n

Do name test specification files the same as the component they test.

\n
\n
\n

Do name test specification files with a suffix of .spec.

\n
\n
\n

Why? Provides a consistent way to quickly identify tests.

\n
\n
\n

Why? Provides pattern matching for karma or other test runners.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Test Type\n \n File Names\n
\n

Components

\n
\n

heroes.component.spec.ts

\n

hero-list.component.spec.ts

\n

hero-detail.component.spec.ts

\n
\n

Services

\n
\n

logger.service.spec.ts

\n

hero.service.spec.ts

\n

filter-text.service.spec.ts

\n
\n

Pipes

\n
\n

ellipsis.pipe.spec.ts

\n

init-caps.pipe.spec.ts

\n
\n

Back to top

\n\n

End-to-End (E2E) test file nameslink

\n

Style 02-11link

\n
\n

Do name end-to-end test specification files after the feature they test with a suffix of .e2e-spec.

\n
\n
\n

Why? Provides a consistent way to quickly identify end-to-end tests.

\n
\n
\n

Why? Provides pattern matching for test runners and build automation.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n
\n Test Type\n \n File Names\n
\n

End-to-End Tests

\n
\n

app.e2e-spec.ts

\n

heroes.e2e-spec.ts

\n
\n

Back to top

\n\n

Angular NgModule nameslink

\n

Style 02-12link

\n
\n

Do append the symbol name with the suffix Module.

\n
\n
\n

Do give the file name the .module.ts extension.

\n
\n
\n

Do name the module after the feature and folder it resides in.

\n
\n
\n

Why? Provides a consistent way to quickly identify and reference modules.

\n
\n
\n

Why? Upper camel case is conventional for identifying objects that can be instantiated using a constructor.

\n
\n
\n

Why? Easily identifies the module as the root of the same named feature.

\n
\n
\n

Do suffix a RoutingModule class name with RoutingModule.

\n
\n
\n

Do end the filename of a RoutingModule with -routing.module.ts.

\n
\n
\n

Why? A RoutingModule is a module dedicated exclusively to configuring the Angular router.\nA consistent class and file name convention make these modules easy to spot and verify.

\n
\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n Symbol Name\n \n File Name\n
\n \n @NgModule({ ... })\n export class AppModule { }\n \n \n

app.module.ts

\n
\n \n @NgModule({ ... })\n export class HeroesModule { }\n \n \n

heroes.module.ts

\n
\n \n @NgModule({ ... })\n export class VillainsModule { }\n \n \n

villains.module.ts

\n
\n \n @NgModule({ ... })\n export class AppRoutingModule { }\n \n \n

app-routing.module.ts

\n
\n \n @NgModule({ ... })\n export class HeroesRoutingModule { }\n \n \n

heroes-routing.module.ts

\n
\n

Back to top

\n

Application structure and NgModuleslink

\n

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.

\n

All of the app's code goes in a folder named src.\nAll feature areas are in their own folder, with their own NgModule.

\n

All content is one asset per file. Each component, service, and pipe is in its own file.\nAll third party vendor scripts are stored in another folder and not in the src folder.\nYou didn't write them and you don't want them cluttering src.\nUse the naming conventions for files in this guide.\nBack to top

\n\n

LIFTlink

\n

Style 04-01link

\n
\n

Do structure the app such that you can Locate code quickly,\nIdentify the code at a glance,\nkeep the Flattest structure you can, and\nTry to be DRY.

\n
\n
\n

Do define the structure to follow these four basic guidelines, listed in order of importance.

\n
\n
\n

Why? LIFT provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly.\nTo confirm your intuition about a particular structure, ask:\ncan I quickly open and start work in all of the related files for this feature?

\n
\n

Back to top

\n\n

Locatelink

\n

Style 04-02link

\n
\n

Do make locating code intuitive, simple, and fast.

\n
\n
\n

Why? To work efficiently you must be able to find files quickly,\nespecially when you do not know (or do not remember) the file names.\nKeeping related files near each other in an intuitive location saves time.\nA descriptive folder structure makes a world of difference to you and the people who come after you.

\n
\n

Back to top

\n\n

Identifylink

\n

Style 04-03link

\n
\n

Do name the file such that you instantly know what it contains and represents.

\n
\n
\n

Do be descriptive with file names and keep the contents of the file to exactly one component.

\n
\n
\n

Avoid files with multiple components, multiple services, or a mixture.

\n
\n
\n

Why? Spend less time hunting and pecking for code, and become more efficient.\nLonger file names are far better than short-but-obscure abbreviated names.

\n
\n
\n

It may be advantageous to deviate from the one-thing-per-file rule when\nyou have a set of small, closely-related features that are better discovered and understood\nin a single file than as multiple files. Be wary of this loophole.

\n
\n

Back to top

\n\n

Flatlink

\n

Style 04-04link

\n
\n

Do keep a flat folder structure as long as possible.

\n
\n
\n

Consider creating sub-folders when a folder reaches seven or more files.

\n
\n
\n

Consider configuring the IDE to hide distracting, irrelevant files such as generated .js and .js.map files.

\n
\n
\n

Why? No one wants to search for a file through seven levels of folders.\nA flat structure is easy to scan.

\n

On the other hand,\npsychologists believe\nthat humans start to struggle when the number of adjacent interesting things exceeds nine.\nSo when a folder has ten or more files, it may be time to create subfolders.

\n

Base your decision on your comfort level.\nUse a flatter structure until there is an obvious value to creating a new folder.

\n
\n

Back to top

\n\n

T-DRY (Try to be DRY)link

\n

Style 04-05link

\n
\n

Do be DRY (Don't Repeat Yourself).

\n
\n
\n

Avoid being so DRY that you sacrifice readability.

\n
\n
\n

Why? Being DRY is important, but not crucial if it sacrifices the other elements of LIFT.\nThat's why it's called T-DRY.\nFor example, it's redundant to name a template hero-view.component.html because\nwith the .html extension, it is obviously a view.\nBut if something is not obvious or departs from a convention, then spell it out.

\n
\n

Back to top

\n\n

Overall structural guidelineslink

\n

Style 04-06link

\n
\n

Do start small but keep in mind where the app is heading down the road.

\n
\n
\n

Do have a near term view of implementation and a long term vision.

\n
\n
\n

Do put all of the app's code in a folder named src.

\n
\n
\n

Consider creating a folder for a component when it has multiple accompanying files (.ts, .html, .css and .spec).

\n
\n
\n

Why? Helps keep the app structure small and easy to maintain in the early stages, while being easy to evolve as the app grows.

\n
\n
\n

Why? Components often have four files (e.g. *.html, *.css, *.ts, and *.spec.ts) and can clutter a folder quickly.

\n
\n\n

Here is a compliant folder and file structure:

\n
\n
\n <project root>\n
\n
\n
\n src\n
\n
\n
\n app\n
\n
\n
\n core\n
\n
\n
\n exception.service.ts|spec.ts\n
\n
\n user-profile.service.ts|spec.ts\n
\n
\n
\n heroes\n
\n
\n
\n hero\n
\n
\n
\n hero.component.ts|html|css|spec.ts\n
\n
\n
\n hero-list\n
\n
\n
\n hero-list.component.ts|html|css|spec.ts\n
\n
\n
\n shared\n
\n
\n
\n hero-button.component.ts|html|css|spec.ts\n
\n
\n hero.model.ts\n
\n
\n hero.service.ts|spec.ts\n
\n
\n
\n heroes.component.ts|html|css|spec.ts\n
\n
\n heroes.module.ts\n
\n
\n heroes-routing.module.ts\n
\n
\n
\n shared\n
\n
\n
\n shared.module.ts\n
\n
\n init-caps.pipe.ts|spec.ts\n
\n
\n filter-text.component.ts|spec.ts\n
\n
\n filter-text.service.ts|spec.ts\n
\n
\n
\n villains\n
\n
\n
\n villain\n
\n
\n
\n ...\n
\n
\n
\n villain-list\n
\n
\n
\n ...\n
\n
\n
\n shared\n
\n
\n
\n ...\n
\n
\n
\n villains.component.ts|html|css|spec.ts\n
\n
\n villains.module.ts\n
\n
\n villains-routing.module.ts\n
\n
\n
\n app.component.ts|html|css|spec.ts\n
\n
\n app.module.ts\n
\n
\n app-routing.module.ts\n
\n
\n
\n main.ts\n
\n
\n index.html\n
\n
\n ...\n
\n
\n
\n node_modules/...\n
\n
\n ...\n
\n
\n
\n
\n

While components in dedicated folders are widely preferred,\nanother option for small apps is to keep components flat (not in a dedicated folder).\nThis adds up to four files to the existing folder, but also reduces the folder nesting.\nWhatever you choose, be consistent.

\n
\n

Back to top

\n\n

Folders-by-feature structurelink

\n

Style 04-07link

\n
\n

Do create folders named for the feature area they represent.

\n
\n
\n

Why? A developer can locate the code and identify what each file represents\nat a glance. The structure is as flat as it can be and there are no repetitive or redundant names.

\n
\n
\n

Why? The LIFT guidelines are all covered.

\n
\n
\n

Why? Helps reduce the app from becoming cluttered through organizing the\ncontent and keeping them aligned with the LIFT guidelines.

\n
\n
\n

Why? When there are a lot of files, for example 10+,\nlocating them is easier with a consistent folder structure\nand more difficult in a flat structure.

\n
\n
\n

Do create an NgModule for each feature area.

\n
\n
\n

Why? NgModules make it easy to lazy load routable features.

\n
\n
\n

Why? NgModules make it easier to isolate, test, and reuse features.

\n
\n
\n

For more information, refer to this folder and file structure example.

\n
\n

Back to top

\n\n

\n

App root modulelink

\n

Style 04-08link

\n
\n

Do create an NgModule in the app's root folder,\nfor example, in /src/app.

\n
\n
\n

Why? Every app requires at least one root NgModule.

\n
\n
\n

Consider naming the root module app.module.ts.

\n
\n
\n

Why? Makes it easier to locate and identify the root module.

\n
\n\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\n\nimport { AppComponent } from './app.component';\nimport { HeroesComponent } from './heroes/heroes.component';\n\n@NgModule({\n imports: [\n BrowserModule,\n ],\n declarations: [\n AppComponent,\n HeroesComponent\n ],\n exports: [ AppComponent ],\n entryComponents: [ AppComponent ]\n})\nexport class AppModule {}\n\n\n

Back to top

\n\n

Feature moduleslink

\n

Style 04-09link

\n
\n

Do create an NgModule for all distinct features in an application;\nfor example, a Heroes feature.

\n
\n
\n

Do place the feature module in the same named folder as the feature area;\nfor example, in app/heroes.

\n
\n
\n

Do name the feature module file reflecting the name of the feature area\nand folder; for example, app/heroes/heroes.module.ts.

\n
\n
\n

Do name the feature module symbol reflecting the name of the feature\narea, folder, and file; for example, app/heroes/heroes.module.ts defines HeroesModule.

\n
\n
\n

Why? A feature module can expose or hide its implementation from other modules.

\n
\n
\n

Why? A feature module identifies distinct sets of related components that comprise the feature area.

\n
\n
\n

Why? A feature module can easily be routed to both eagerly and lazily.

\n
\n
\n

Why? A feature module defines clear boundaries between specific functionality and other application features.

\n
\n
\n

Why? A feature module helps clarify and make it easier to assign development responsibilities to different teams.

\n
\n
\n

Why? A feature module can easily be isolated for testing.

\n
\n

Back to top

\n\n

Shared feature modulelink

\n

Style 04-10link

\n
\n

Do create a feature module named SharedModule in a shared folder;\nfor example, app/shared/shared.module.ts defines SharedModule.

\n
\n
\n

Do declare components, directives, and pipes in a shared module when those\nitems will be re-used and referenced by the components declared in other feature modules.

\n
\n
\n

Consider using the name SharedModule when the contents of a shared\nmodule are referenced across the entire application.

\n
\n
\n

Consider not providing services in shared modules. Services are usually\nsingletons that are provided once for the entire application or\nin a particular feature module. There are exceptions, however. For example, in the sample code that follows, notice that the SharedModule provides FilterTextService. This is acceptable here because the service is stateless;that is, the consumers of the service aren't impacted by new instances.

\n
\n
\n

Do import all modules required by the assets in the SharedModule;\nfor example, CommonModule and FormsModule.

\n
\n
\n

Why? SharedModule will contain components, directives and pipes\nthat may need features from another common module; for example,\nngFor in CommonModule.

\n
\n
\n

Do declare all components, directives, and pipes in the SharedModule.

\n
\n
\n

Do export all symbols from the SharedModule that other feature modules need to use.

\n
\n
\n

Why? SharedModule exists to make commonly used components, directives and pipes available for use in the templates of components in many other modules.

\n
\n
\n

Avoid specifying app-wide singleton providers in a SharedModule. Intentional singletons are OK. Take care.

\n
\n
\n

Why? A lazy loaded feature module that imports that shared module will make its own copy of the service and likely have undesirable results.

\n
\n
\n

Why? You don't want each module to have its own separate instance of singleton services.\nYet there is a real danger of that happening if the SharedModule provides a service.

\n
\n
\n
\n src\n
\n
\n
\n app\n
\n
\n
\n shared\n
\n
\n
\n shared.module.ts\n
\n
\n init-caps.pipe.ts|spec.ts\n
\n
\n filter-text.component.ts|spec.ts\n
\n
\n filter-text.service.ts|spec.ts\n
\n
\n
\n app.component.ts|html|css|spec.ts\n
\n
\n app.module.ts\n
\n
\n app-routing.module.ts\n
\n
\n
\n main.ts\n
\n
\n index.html\n
\n
\n
\n ...\n
\n
\n\n\n \nimport { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule } from '@angular/forms';\n\nimport { FilterTextComponent } from './filter-text/filter-text.component';\nimport { FilterTextService } from './filter-text/filter-text.service';\nimport { InitCapsPipe } from './init-caps.pipe';\n\n@NgModule({\n imports: [CommonModule, FormsModule],\n declarations: [\n FilterTextComponent,\n InitCapsPipe\n ],\n providers: [FilterTextService],\n exports: [\n CommonModule,\n FormsModule,\n FilterTextComponent,\n InitCapsPipe\n ]\n})\nexport class SharedModule { }\n\n\n\n\n \nimport { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({ name: 'initCaps' })\nexport class InitCapsPipe implements PipeTransform {\n transform = (value: string) => value;\n}\n\n\n\n\n \nimport { Component, EventEmitter, Output } from '@angular/core';\n\n@Component({\n selector: 'toh-filter-text',\n template: '<input type=\"text\" id=\"filterText\" [(ngModel)]=\"filter\" (keyup)=\"filterChanged($event)\" />'\n})\nexport class FilterTextComponent {\n @Output() changed: EventEmitter<string>;\n\n filter: string;\n\n constructor() {\n this.changed = new EventEmitter<string>();\n }\n\n clear() {\n this.filter = '';\n }\n\n filterChanged(event: any) {\n event.preventDefault();\n console.log(`Filter Changed: ${this.filter}`);\n this.changed.emit(this.filter);\n }\n}\n\n\n\n\n \nimport { Injectable } from '@angular/core';\n\n@Injectable()\nexport class FilterTextService {\n constructor() {\n console.log('Created an instance of FilterTextService');\n }\n\n filter(data: string, props: Array<string>, originalList: Array<any>) {\n let filteredList: any[];\n if (data && props && originalList) {\n data = data.toLowerCase();\n const filtered = originalList.filter(item => {\n let match = false;\n for (const prop of props) {\n if (item[prop].toString().toLowerCase().indexOf(data) > -1) {\n match = true;\n break;\n }\n }\n return match;\n });\n filteredList = filtered;\n } else {\n filteredList = originalList;\n }\n return filteredList;\n }\n}\n\n\n\n\n \nimport { Component } from '@angular/core';\n\nimport { FilterTextService } from '../shared/filter-text/filter-text.service';\n\n@Component({\n selector: 'toh-heroes',\n templateUrl: './heroes.component.html'\n})\nexport class HeroesComponent {\n\n heroes = [\n { id: 1, name: 'Windstorm' },\n { id: 2, name: 'Bombasto' },\n { id: 3, name: 'Magneta' },\n { id: 4, name: 'Tornado' }\n ];\n\n filteredHeroes = this.heroes;\n\n constructor(private filterService: FilterTextService) { }\n\n filterChanged(searchText: string) {\n this.filteredHeroes = this.filterService.filter(searchText, ['id', 'name'], this.heroes);\n }\n}\n\n\n\n\n\n \n<div>This is heroes component</div>\n<ul>\n <li *ngFor=\"let hero of filteredHeroes\">\n {{hero.name}}\n </li>\n</ul>\n<toh-filter-text (changed)=\"filterChanged($event)\"></toh-filter-text>\n\n\n\n\n\n

Back to top

\n\n

Lazy Loaded folderslink

\n

Style 04-11link

\n

A distinct application feature or workflow may be lazy loaded or loaded on demand rather than when the application starts.

\n
\n

Do put the contents of lazy loaded features in a lazy loaded folder.\nA typical lazy loaded folder contains a routing component, its child components, and their related assets and modules.

\n
\n
\n

Why? The folder makes it easy to identify and isolate the feature content.

\n
\n

Back to top

\n\n

Never directly import lazy loaded folderslink

\n

Style 04-12link

\n
\n

Avoid allowing modules in sibling and parent folders to directly import a module in a lazy loaded feature.

\n
\n
\n

Why? Directly importing and using a module will load it immediately when the intention is to load it on demand.

\n
\n

Back to top

\n

Componentslink

\n\n

Components as elementslink

\n

Style 05-03link

\n
\n

Consider giving components an element selector, as opposed to attribute or class selectors.

\n
\n
\n

Why? Components have templates containing HTML and optional Angular template syntax.\nThey display content.\nDevelopers place components on the page as they would native HTML elements and web components.

\n
\n
\n

Why? It is easier to recognize that a symbol is a component by looking at the template's html.

\n
\n
\n

There are a few cases where you give a component an attribute, such as when you want to augment a built-in element. For example, Material Design uses this technique with <button mat-button>. However, you wouldn't use this technique on a custom element.

\n
\n\n/* avoid */\n\n@Component({\n selector: '[tohHeroButton]',\n templateUrl: './hero-button.component.html'\n})\nexport class HeroButtonComponent {}\n\n\n\n<!-- avoid -->\n\n<div tohHeroButton></div>\n\n\n\n\n\n \n@Component({\n selector: 'toh-hero-button',\n templateUrl: './hero-button.component.html'\n})\nexport class HeroButtonComponent {}\n\n\n\n \n<toh-hero-button></toh-hero-button>\n\n\n\n\n\n

Back to top

\n\n

Extract templates and styles to their own fileslink

\n

Style 05-04link

\n
\n

Do extract templates and styles into a separate file, when more than 3 lines.

\n
\n
\n

Do name the template file [component-name].component.html, where [component-name] is the component name.

\n
\n
\n

Do name the style file [component-name].component.css, where [component-name] is the component name.

\n
\n
\n

Do specify component-relative URLs, prefixed with ./.

\n
\n
\n

Why? Large, inline templates and styles obscure the component's purpose and implementation, reducing readability and maintainability.

\n
\n
\n

Why? In most editors, syntax hints and code snippets aren't available when developing inline templates and styles.\nThe Angular TypeScript Language Service (forthcoming) promises to overcome this deficiency for HTML templates\nin those editors that support it; it won't help with CSS styles.

\n
\n
\n

Why? A component relative URL requires no change when you move the component files, as long as the files stay together.

\n
\n
\n

Why? The ./ prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'toh-heroes',\n template: `\n <div>\n <h2>My Heroes</h2>\n <ul class=\"heroes\">\n <li *ngFor=\"let hero of heroes | async\" (click)=\"selectedHero=hero\">\n <span class=\"badge\">{{hero.id}}</span> {{hero.name}}\n </li>\n </ul>\n <div *ngIf=\"selectedHero\">\n <h2>{{selectedHero.name | uppercase}} is my hero</h2>\n </div>\n </div>\n `,\n styles: [`\n .heroes {\n margin: 0 0 2em 0;\n list-style-type: none;\n padding: 0;\n width: 15em;\n }\n .heroes li {\n cursor: pointer;\n position: relative;\n left: 0;\n background-color: #EEE;\n margin: .5em;\n padding: .3em 0;\n height: 1.6em;\n border-radius: 4px;\n }\n .heroes .badge {\n display: inline-block;\n font-size: small;\n color: white;\n padding: 0.8em 0.7em 0 0.7em;\n background-color: #607D8B;\n line-height: 1em;\n position: relative;\n left: -1px;\n top: -4px;\n height: 1.8em;\n margin-right: .8em;\n border-radius: 4px 0 0 4px;\n }\n `]\n})\nexport class HeroesComponent implements OnInit {\n heroes: Observable<Hero[]>;\n selectedHero: Hero;\n\n constructor(private heroService: HeroService) { }\n\n ngOnInit() {\n this.heroes = this.heroService.getHeroes();\n }\n}\n\n\n\n\n \n@Component({\n selector: 'toh-heroes',\n templateUrl: './heroes.component.html',\n styleUrls: ['./heroes.component.css']\n})\nexport class HeroesComponent implements OnInit {\n heroes: Observable<Hero[]>;\n selectedHero: Hero;\n\n constructor(private heroService: HeroService) { }\n\n ngOnInit() {\n this.heroes = this.heroService.getHeroes();\n }\n}\n\n\n\n \n<div>\n <h2>My Heroes</h2>\n <ul class=\"heroes\">\n <li *ngFor=\"let hero of heroes | async\" (click)=\"selectedHero=hero\">\n <span class=\"badge\">{{hero.id}}</span> {{hero.name}}\n </li>\n </ul>\n <div *ngIf=\"selectedHero\">\n <h2>{{selectedHero.name | uppercase}} is my hero</h2>\n </div>\n</div>\n\n\n\n\n \n.heroes {\n margin: 0 0 2em 0;\n list-style-type: none;\n padding: 0;\n width: 15em;\n}\n.heroes li {\n cursor: pointer;\n position: relative;\n left: 0;\n background-color: #EEE;\n margin: .5em;\n padding: .3em 0;\n height: 1.6em;\n border-radius: 4px;\n}\n.heroes .badge {\n display: inline-block;\n font-size: small;\n color: white;\n padding: 0.8em 0.7em 0 0.7em;\n background-color: #607D8B;\n line-height: 1em;\n position: relative;\n left: -1px;\n top: -4px;\n height: 1.8em;\n margin-right: .8em;\n border-radius: 4px 0 0 4px;\n}\n\n\n\n\n\n

Back to top

\n\n

Decorate input and output propertieslink

\n

Style 05-12link

\n
\n

Do use the @Input() and @Output() class decorators instead of the inputs and outputs properties of the\n@Directive and @Component metadata:

\n
\n
\n

Consider placing @Input() or @Output() on the same line as the property it decorates.

\n
\n
\n

Why? It is easier and more readable to identify which properties in a class are inputs or outputs.

\n
\n
\n

Why? If you ever need to rename the property or event name associated with\n@Input() or @Output(), you can modify it in a single place.

\n
\n
\n

Why? The metadata declaration attached to the directive is shorter and thus more readable.

\n
\n
\n

Why? Placing the decorator on the same line usually makes for shorter code and still easily identifies the property as an input or output.\nPut it on the line above when doing so is clearly more readable.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'toh-hero-button',\n template: `<button></button>`,\n inputs: [\n 'label'\n ],\n outputs: [\n 'heroChange'\n ]\n})\nexport class HeroButtonComponent {\n heroChange = new EventEmitter<any>();\n label: string;\n}\n\n\n\n@Component({\n selector: 'toh-hero-button',\n template: `<button>{{label}}</button>`\n})\nexport class HeroButtonComponent {\n @Output() heroChange = new EventEmitter<any>();\n @Input() label: string;\n}\n\n\n

Back to top

\n\n

Avoid aliasing inputs and outputslink

\n

Style 05-13link

\n
\n

Avoid input and output aliases except when it serves an important purpose.

\n
\n
\n

Why? Two names for the same property (one private, one public) is inherently confusing.

\n
\n
\n

Why? You should use an alias when the directive name is also an input property,\nand the directive name doesn't describe the property.

\n
\n\n/* avoid pointless aliasing */\n\n@Component({\n selector: 'toh-hero-button',\n template: `<button>{{label}}</button>`\n})\nexport class HeroButtonComponent {\n // Pointless aliases\n @Output('heroChangeEvent') heroChange = new EventEmitter<any>();\n @Input('labelAttribute') label: string;\n}\n\n\n\n<!-- avoid -->\n\n<toh-hero-button labelAttribute=\"OK\" (changeEvent)=\"doSomething()\">\n</toh-hero-button>\n\n\n\n\n\n \n@Component({\n selector: 'toh-hero-button',\n template: `<button>{{label}}</button>`\n})\nexport class HeroButtonComponent {\n // No aliases\n @Output() heroChange = new EventEmitter<any>();\n @Input() label: string;\n}\n\n\n\n \nimport { Directive, ElementRef, Input, OnChanges } from '@angular/core';\n\n@Directive({ selector: '[heroHighlight]' })\nexport class HeroHighlightDirective implements OnChanges {\n\n // Aliased because `color` is a better property name than `heroHighlight`\n @Input('heroHighlight') color: string;\n\n constructor(private el: ElementRef) {}\n\n ngOnChanges() {\n this.el.nativeElement.style.backgroundColor = this.color || 'yellow';\n }\n}\n\n\n\n\n \n<toh-hero-button label=\"OK\" (change)=\"doSomething()\">\n</toh-hero-button>\n\n<!-- `heroHighlight` is both the directive name and the data-bound aliased property name -->\n<h3 heroHighlight=\"skyblue\">The Great Bombasto</h3>\n\n\n\n\n\n

Back to top

\n\n

Member sequencelink

\n

Style 05-14link

\n
\n

Do place properties up top followed by methods.

\n
\n
\n

Do place private members after public members, alphabetized.

\n
\n
\n

Why? Placing members in a consistent sequence makes it easy to read and\nhelps instantly identify which members of the component serve which purpose.

\n
\n\n/* avoid */\n\nexport class ToastComponent implements OnInit {\n\n private defaults = {\n title: '',\n message: 'May the Force be with you'\n };\n message: string;\n title: string;\n private toastElement: any;\n\n ngOnInit() {\n this.toastElement = document.getElementById('toh-toast');\n }\n\n // private methods\n private hide() {\n this.toastElement.style.opacity = 0;\n window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);\n }\n\n activate(message = this.defaults.message, title = this.defaults.title) {\n this.title = title;\n this.message = message;\n this.show();\n }\n\n private show() {\n console.log(this.message);\n this.toastElement.style.opacity = 1;\n this.toastElement.style.zIndex = 9999;\n\n window.setTimeout(() => this.hide(), 2500);\n }\n}\n\n\n\nexport class ToastComponent implements OnInit {\n // public properties\n message: string;\n title: string;\n\n // private fields\n private defaults = {\n title: '',\n message: 'May the Force be with you'\n };\n private toastElement: any;\n\n // public methods\n activate(message = this.defaults.message, title = this.defaults.title) {\n this.title = title;\n this.message = message;\n this.show();\n }\n\n ngOnInit() {\n this.toastElement = document.getElementById('toh-toast');\n }\n\n // private methods\n private hide() {\n this.toastElement.style.opacity = 0;\n window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);\n }\n\n private show() {\n console.log(this.message);\n this.toastElement.style.opacity = 1;\n this.toastElement.style.zIndex = 9999;\n window.setTimeout(() => this.hide(), 2500);\n }\n}\n\n\n

Back to top

\n\n

Delegate complex component logic to serviceslink

\n

Style 05-15link

\n
\n

Do limit logic in a component to only that required for the view. All other logic should be delegated to services.

\n
\n
\n

Do move reusable logic to services and keep components simple and focused on their intended purpose.

\n
\n
\n

Why? Logic may be reused by multiple components when placed within a service and exposed via a function.

\n
\n
\n

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.

\n
\n
\n

Why? Removes dependencies and hides implementation details from the component.

\n
\n
\n

Why? Keeps the component slim, trim, and focused.

\n
\n\n/* avoid */\n\nimport { OnInit } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\nimport { Observable } from 'rxjs';\nimport { catchError, finalize } from 'rxjs/operators';\n\nimport { Hero } from '../shared/hero.model';\n\nconst heroesUrl = 'http://angular.io';\n\nexport class HeroListComponent implements OnInit {\n heroes: Hero[];\n constructor(private http: HttpClient) {}\n getHeroes() {\n this.heroes = [];\n this.http.get(heroesUrl).pipe(\n catchError(this.catchBadResponse),\n finalize(() => this.hideSpinner())\n ).subscribe((heroes: Hero[]) => this.heroes = heroes);\n }\n ngOnInit() {\n this.getHeroes();\n }\n\n private catchBadResponse(err: any, source: Observable<any>) {\n // log and handle the exception\n return new Observable();\n }\n\n private hideSpinner() {\n // hide the spinner\n }\n}\n\n\n\n\nimport { Component, OnInit } from '@angular/core';\n\nimport { Hero, HeroService } from '../shared';\n\n@Component({\n selector: 'toh-hero-list',\n template: `...`\n})\nexport class HeroListComponent implements OnInit {\n heroes: Hero[];\n constructor(private heroService: HeroService) {}\n getHeroes() {\n this.heroes = [];\n this.heroService.getHeroes()\n .subscribe(heroes => this.heroes = heroes);\n }\n ngOnInit() {\n this.getHeroes();\n }\n}\n\n\n

Back to top

\n\n

Don't prefix output propertieslink

\n

Style 05-16link

\n
\n

Do name events without the prefix on.

\n
\n
\n

Do name event handler methods with the prefix on followed by the event name.

\n
\n
\n

Why? This is consistent with built-in events such as button clicks.

\n
\n
\n

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.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'toh-hero',\n template: `...`\n})\nexport class HeroComponent {\n @Output() onSavedTheDay = new EventEmitter<boolean>();\n}\n\n\n\n<!-- avoid -->\n\n<toh-hero (onSavedTheDay)=\"onSavedTheDay($event)\"></toh-hero>\n\n\n\n\n\n \nexport class HeroComponent {\n @Output() savedTheDay = new EventEmitter<boolean>();\n}\n\n\n\n \n<toh-hero (savedTheDay)=\"onSavedTheDay($event)\"></toh-hero>\n\n\n\n\n\n

Back to top

\n\n

Put presentation logic in the component classlink

\n

Style 05-17link

\n
\n

Do put presentation logic in the component class, and not in the template.

\n
\n
\n

Why? Logic will be contained in one place (the component class) instead of being spread in two places.

\n
\n
\n

Why? Keeping the component's presentation logic in the class instead of the template improves testability, maintainability, and reusability.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'toh-hero-list',\n template: `\n <section>\n Our list of heroes:\n <toh-hero *ngFor=\"let hero of heroes\" [hero]=\"hero\">\n </toh-hero>\n Total powers: {{totalPowers}}<br>\n Average power: {{totalPowers / heroes.length}}\n </section>\n `\n})\nexport class HeroListComponent {\n heroes: Hero[];\n totalPowers: number;\n}\n\n\n\n@Component({\n selector: 'toh-hero-list',\n template: `\n <section>\n Our list of heroes:\n <toh-hero *ngFor=\"let hero of heroes\" [hero]=\"hero\">\n </toh-hero>\n Total powers: {{totalPowers}}<br>\n Average power: {{avgPower}}\n </section>\n `\n})\nexport class HeroListComponent {\n heroes: Hero[];\n totalPowers: number;\n\n get avgPower() {\n return this.totalPowers / this.heroes.length;\n }\n}\n\n\n

Back to top

\n

Initialize inputslink

\n

Style 05-18link

\n

TypeScript's --strictPropertyInitialization compiler option ensures that a class initializes its properties during construction. When enabled, this option causes the TypeScript compiler to report an error if the class does not set a value to any property that is not explicitly marked as optional.

\n

By design, Angular treats all @Input properties as optional. When possible, you should satisfy --strictPropertyInitialization by providing a default value.

\n\n@Component({\n selector: 'toh-hero',\n template: `...`\n})\nexport class HeroComponent {\n @Input() id = 'default_id';\n}\n\n\n

If the property is hard to construct a default value for, use ? to explicitly mark the property as optional.

\n\n@Component({\n selector: 'toh-hero',\n template: `...`\n})\nexport class HeroComponent {\n @Input() id?: string;\n\n process() {\n if (this.id) {\n // ...\n }\n }\n}\n\n\n

You may want to have a required @Input field, meaning all your component users are required to pass that attribute. In such cases, use a default value. Just suppressing the TypeScript error with ! is insufficient and should be avoided because it will prevent the type checker ensure the input value is provided.

\n\n@Component({\n selector: 'toh-hero',\n template: `...`\n})\nexport class HeroComponent {\n // The exclamation mark suppresses errors that a property is\n // not initialized.\n // Ignoring this enforcement can prevent the type checker\n // from finding potential issues.\n @Input() id!: string;\n}\n\n\n

Directiveslink

\n\n

Use directives to enhance an elementlink

\n

Style 06-01link

\n
\n

Do use attribute directives when you have presentation logic without a template.

\n
\n
\n

Why? Attribute directives don't have an associated template.

\n
\n
\n

Why? An element may have more than one attribute directive applied.

\n
\n\n@Directive({\n selector: '[tohHighlight]'\n})\nexport class HighlightDirective {\n @HostListener('mouseover') onMouseEnter() {\n // do highlight work\n }\n}\n\n\n\n<div tohHighlight>Bombasta</div>\n\n\n\n

Back to top

\n\n

HostListener/HostBinding decorators versus host metadatalink

\n

Style 06-03link

\n
\n

Consider preferring the @HostListener and @HostBinding to the\nhost property of the @Directive and @Component decorators.

\n
\n
\n

Do be consistent in your choice.

\n
\n
\n

Why? The property associated with @HostBinding or the method associated with @HostListener\ncan be modified only in a single place—in the directive's class.\nIf you use the host metadata property, you must modify both the property/method declaration in the\ndirective's class and the metadata in the decorator associated with the directive.

\n
\n\nimport { Directive, HostBinding, HostListener } from '@angular/core';\n\n@Directive({\n selector: '[tohValidator]'\n})\nexport class ValidatorDirective {\n @HostBinding('attr.role') role = 'button';\n @HostListener('mouseenter') onMouseEnter() {\n // do work\n }\n}\n\n\n\n

Compare with the less preferred host metadata alternative.

\n
\n

Why? The host metadata is only one term to remember and doesn't require extra ES imports.

\n
\n\nimport { Directive } from '@angular/core';\n\n@Directive({\n selector: '[tohValidator2]',\n host: {\n '[attr.role]': 'role',\n '(mouseenter)': 'onMouseEnter()'\n }\n})\nexport class Validator2Directive {\n role = 'button';\n onMouseEnter() {\n // do work\n }\n}\n\n\n\n

Back to top

\n

Serviceslink

\n\n

Services are singletonslink

\n

Style 07-01link

\n
\n

Do use services as singletons within the same injector. Use them for sharing data and functionality.

\n
\n
\n

Why? Services are ideal for sharing methods across a feature area or an app.

\n
\n
\n

Why? Services are ideal for sharing stateful in-memory data.

\n
\n\nexport class HeroService {\n constructor(private http: HttpClient) { }\n\n getHeroes() {\n return this.http.get<Hero[]>('api/heroes');\n }\n}\n\n\n

Back to top

\n\n

Single responsibilitylink

\n

Style 07-02link

\n
\n

Do create services with a single responsibility that is encapsulated by its context.

\n
\n
\n

Do create a new service once the service begins to exceed that singular purpose.

\n
\n
\n

Why? When a service has multiple responsibilities, it becomes difficult to test.

\n
\n
\n

Why? When a service has multiple responsibilities, every component or service that injects it now carries the weight of them all.

\n
\n

Back to top

\n\n

Providing a servicelink

\n

Style 07-03link

\n
\n

Do provide a service with the app root injector in the @Injectable decorator of the service.

\n
\n
\n

Why? The Angular injector is hierarchical.

\n
\n
\n

Why? When you provide the service to a root injector, that instance of the service is shared and available in every class that needs the service. This is ideal when a service is sharing methods or state.

\n
\n
\n

Why? When you register a service in the @Injectable decorator of the service, optimization tools such as those used by the Angular CLI's production builds can perform tree shaking and remove services that aren't used by your app.

\n
\n
\n

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.

\n
\n\n@Injectable({\n providedIn: 'root',\n})\nexport class Service {\n}\n\n\n\n

Back to top

\n\n

Use the @Injectable() class decoratorlink

\n

Style 07-04link

\n
\n

Do use the @Injectable() class decorator instead of the @Inject parameter decorator when using types as tokens for the dependencies of a service.

\n
\n
\n

Why? The Angular Dependency Injection (DI) mechanism resolves a service's own\ndependencies based on the declared types of that service's constructor parameters.

\n
\n
\n

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.

\n
\n\n/* avoid */\n\nexport class HeroArena {\n constructor(\n @Inject(HeroService) private heroService: HeroService,\n @Inject(HttpClient) private http: HttpClient) {}\n}\n\n\n\n@Injectable()\nexport class HeroArena {\n constructor(\n private heroService: HeroService,\n private http: HttpClient) {}\n}\n\n\n

Back to top

\n

Data Serviceslink

\n\n

Talk to the server through a servicelink

\n

Style 08-01link

\n
\n

Do refactor logic for making data operations and interacting with data to a service.

\n
\n
\n

Do make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.

\n
\n
\n

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.

\n
\n
\n

Why? This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.

\n
\n
\n

Why? The details of data management, such as headers, HTTP methods,\ncaching, error handling, and retry logic, are irrelevant to components\nand other data consumers.

\n

A data service encapsulates these details. It's easier to evolve these\ndetails inside the service without affecting its consumers. And it's\neasier to test the consumers with mock service implementations.

\n
\n

Back to top

\n

Lifecycle hookslink

\n

Use Lifecycle hooks to tap into important events exposed by Angular.

\n

Back to top

\n\n

Implement lifecycle hook interfaceslink

\n

Style 09-01link

\n
\n

Do implement the lifecycle hook interfaces.

\n
\n
\n

Why? Lifecycle interfaces prescribe typed method\nsignatures. Use those signatures to flag spelling and syntax mistakes.

\n
\n\n/* avoid */\n\n@Component({\n selector: 'toh-hero-button',\n template: `<button>OK<button>`\n})\nexport class HeroButtonComponent {\n onInit() { // misspelled\n console.log('The component is initialized');\n }\n}\n\n\n\n@Component({\n selector: 'toh-hero-button',\n template: `<button>OK</button>`\n})\nexport class HeroButtonComponent implements OnInit {\n ngOnInit() {\n console.log('The component is initialized');\n }\n}\n\n\n

Back to top

\n

Appendixlink

\n

Useful tools and tips for Angular.

\n

Back to top

\n\n

File templates and snippetslink

\n

Style A-02link

\n
\n

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.

\n
\n
\n

Consider using snippets for Visual Studio Code that follow these styles and guidelines.

\n\n \"Use\n\n

Consider using snippets for Atom that follow these styles and guidelines.

\n

Consider using snippets for Sublime Text that follow these styles and guidelines.

\n

Consider using snippets for Vim that follow these styles and guidelines.

\n
\n

Back to top

\n\n \n
\n\n\n" }