include ../_util-fns :marked Welcome to the Angular 2 Guide of Style (version 2) ## Purpose If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular applications, then step right in. The purpose of this style guide is to provide guidance on building Angular applications by showing the conventions we use and, more importantly, why we choose them. .l-main-section a(id='toc') :marked ## Table of Contents 1. [Single Responsibility](#single-responsibility) 1. [File Naming](#file-naming) 1. [Symbol Naming](#symbol-naming) 1. [Application Structure](#application-structure) 1. [Components](#components) 1. [Directives](#directives) 1. [Lifecycle Hooks](#lifecycle-hooks) 1. [Services](#services) 1. [Data Services](#data-services) 1. [Routing](#routing) 1. [Appendix](#appendix) :marked ## Single Responsibility ### Rule of 1 #### Style 01-01 Define 1 component per file, recommended to be less than 400 lines of code. **Why?** One component per file promotes easier unit testing and mocking. **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. The following example defines the `AppComponent`, handles the bootstrapping, and shared functions all in the same file. The key is to make the code more reusable, easier to read, and less mistake prone. +makeExample('style-guide/ts/001/app/placeholder.ts', '001-1', 'app.component.ts (component)') :marked The same components are now separated into their own files. +makeTabs( 'style-guide/ts/001/app/main.ts,style-guide/ts/001/app/app.component.ts,style-guide/ts/001/app/hero.service.ts,style-guide/ts/001/app/hero.model.ts', '', 'app/main.ts, app/app.component.ts, app/hero.service.ts, app/hero.model.ts') :marked As the app grows, this rule becomes even more important. Back to top :marked ### Small Functions #### Style 01-02 - Define small functions, no more than 75 LOC (less is better). **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. Back to top :marked ## Naming - Use consistent names for all components following a pattern that describes the component's feature then (optionally) its type. My recommended pattern is `feature.type.js`. There are 2 names for most assets: * the file name (`avengers.component.ts`) * the registered component name with Angular (`Component`) **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 you find your 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. Back to top :marked ### Separate File Names with Dots and Dashes #### Style 02-01 - Use dashes to separate words. Use dots to separate the descriptive name from the type. - Use consistent names for all components following a pattern that describes the component's feature then its type. A recommended pattern is `feature.type.ts`. - Use conventional suffixes for the types including `*.service.ts`, `*.component.ts`, `*.pipe.ts`. Invent other suffixes where desired for your team, but take care in having too many. **Why?** Provides a consistent way to quickly identify what is in the file. **Why?** Provides a consistent way to quickly find a specific file using an editor or IDE's fuzzy search techniques. **Why?** Provides pattern matching for any automated tasks. Back to top :marked ### Names #### Style 02-02 - Use consistent names for all assets named after what they represent. - Use UpperCamelCase for symbols. Match the name of the symbol to the naming of the file. - Append the symbol name with a suffix that it represents. **Why?** Provides a consistent way to quickly identify and reference assets. **Why?** UpperCamelCase is conventional for identifying object that can be instantiated using a constructor. **Why?** The `Component` suffix is more commonly used and is more explicitly descriptive. ```typescript /* recommended */ AppComponent // app.component.ts HeroesComponent // heroes.component.ts HeroListComponent // hero-list.component.ts HeroDetailComponent // hero-detail.component.ts /* recommended */ ValidationDirective // validation.directive.ts ``` Back to top :marked ### Service Names #### Style 02-03 - Use consistent names for all services named after their feature. Use UpperCamelCase for services. Suffix services with `Service` when it is not clear what they are (e.g. when they are nouns). **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. ```typescript HeroDataService // hero-data.service.ts CreditService // credit.service.ts LoggerService // logger.service.ts ``` Back to top :marked ### Bootstrapping #### Style 02-04 - Place bootstrapping and platform logic for the app in a file named `main.ts`. - Do not put 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 familar convention from other technology platforms. Back to top :marked ### Pipe Names #### Style 02-10 - Use consistent names for all pipes named after their feature. **Why?** Provides a consistent way to quickly identify and reference pipes. ```typescript EllipsisPipe // ellipsis.pipe.ts InitCapsPipe // init-caps.pipe.ts ``` Back to top :marked ### Test File Names #### Style 02-12 - Name test specifications similar to the component they test with a suffix of `.spec`. **Why?** Provides a consistent way to quickly identify components. **Why?** Provides pattern matching for [karma](http://karma-runner.github.io/) or other test runners. ``` // recommended // Components heroes.component.spec.ts hero-list.component.spec.ts hero-detail.component.spec.ts // Services logger.service.spec.ts hero.service.spec.ts exception.service.spec.ts filter-text.service.spec.ts // Pipes ellipsis.pipe.spec.ts init-caps.pipe.spec.ts ``` Back to top :marked ### Route Naming #### Style 02-31 - Use the naming convention for the routes with the component name without the Component suffix. **Why?** This maps the route name to the component and makes it easy to identify. ```typescript { path: '/dashboard', name: 'Dashboard', component: DashboardComponent } ``` Back to top :marked ## Application Structure TODO Back to top :marked ### LIFT #### Style 04-40 - Structure your app such that you can `L`ocate your code quickly, `I`dentify the code at a glance, keep the `F`lattest structure you can, and `T`ry to stay DRY. The structure should follow these 4 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. Another way to check your app structure is to ask yourself: How quickly can you open and work in all of the related files for a feature? Back to top :marked ### Locate #### Style 04-41 - Make locating your code intuitive, simple and fast. **Why?** I find this to be super important for a project. If the team cannot find the files they need to work on quickly, they will not be able to work as efficiently as possible, and the structure needs to change. You may not know the file name or where its related files are, so putting them in the most intuitive locations and near each other saves a ton of time. A descriptive folder structure can help with this. Back to top :marked ### Identify #### Style 04-42 - When you look at a file you should instantly know what it contains and represents. **Why?** You spend less time hunting and pecking for code, and become more efficient. If this means you want longer file names, then so be it. Be descriptive with file names and keeping the contents of the file to exactly 1 component. Avoid files with multiple controllers, multiple services, or a mixture. There are deviations of the 1 per file rule when I have a set of very small features that are all related to each other, they are still easily identifiable. Back to top :marked ### Flat #### Style 04-43 - Keep a flat folder structure as long as possible. When you get to 7+ files, begin considering separation. **Why?** Nobody wants to search 7 levels of folders to find a file. Think about menus on web sites … anything deeper than 2 should take serious consideration. In a folder structure there is no hard and fast number rule, but when a folder has 7-10 files, that may be time to create subfolders. Base it on your comfort level. Use a flatter structure until there is an obvious value (to help the rest of LIFT) in creating a new folder. Back to top :marked ### T-DRY (Try to Stick to DRY) #### Style 04-44 - Be DRY, but don't go nuts and sacrifice readability. **Why?** Being DRY is important, but not crucial if it sacrifices the others in LIFT, which is why I call it T-DRY. I don’t want to type hero-view.html for a view because, well, it’s obviously a view. If it is not obvious or by convention, then I name it. Back to top :marked ### Overall Guidelines #### Style 04-50 - Have a near term view of implementation and a long term vision. In other words, start small but keep in mind on where the app is heading down the road. All of the app's code goes in a root folder named `app`. All content is 1 feature per file. Each component, service, pipe is in its own file. All 3rd party vendor scripts are stored in another root folder and not in the `app` folder. I didn't write them and I don't want them cluttering my app. **example coming soon** Back to top :marked ### Layout #### Style 04-51 - Place components that define the overall layout of the application in a folder named `layout`. These may include a shell view and component may act as the container for the app, navigation, menus, content areas, and other regions. **Why?** Organizes all layout in a single place re-used throughout the application. Back to top :marked ### Folders-by-Feature Structure #### Style 04-52 - Create folders named for the feature they represent. When a folder grows to contain more than 7 files, start to consider creating a folder for them. Your threshold may be different, so adjust as needed. **Why?** A developer can locate the code, identify what each file represents at a glance, the structure is flat as can be, and there is no repetitive nor 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 (10+) locating them is easier with a consistent folder structures and more difficult in flat structures. **example coming soon** Back to top :marked ## Components ### Components Selector Naming #### Style 05-02 - Use `kebab-case` for naming the element selectors of your components. **Why?**: Keeps the element names consistent with the specification for [Custom Elements](https://www.w3.org/TR/custom-elements/). ```typescript /* avoid */ @Component({ selector: 'heroButton' }) class HeroButtonComponent {} ``` ```typescript /* recommended */ @Component({ selector: 'hero-button' }) class HeroButtonComponent {} ``` ```html /* recommended */ ``` Back to top :marked ### Components as Elements #### Style 05-03 - Define Components as elements via the selector. **Why?**: Components have templates containing HTML and optional Angular template syntax. They are most associated with putting content on a page, and thus are more closely aligned with elements. **Why?**: Components are derived from Directives, and thus their selectors can be elements, attributes, or other selectors. Defining the selector as an element provides consistency for components that represent content with a template. ```typescript /* avoid */ @Component({ selector: '[hero-button]' }) class HeroButtonComponent {} ``` ```html /* avoid */
``` ```typescript /* recommended */ @Component({ selector: 'hero-button' }) class HeroButtonComponent {} ``` ```html /* recommended */ ``` Back to top :marked ### Extract Template and Styles to Their Own Files #### Style 05-04 - Extract templates and styles into a separate file, when more than 3 lines. - Name the template file `[component-name].component.html`, where [component-name] is your component name. - Name the style file `[component-name].component.css`, where [component-name] is your component name. **Why?**: Syntax hints for inline templates in (*.js and *.ts) code files are not supported by some editors. **Why?**: A component file's logic is easier to read when not mixed with inline template and styles. ```typescript /* avoid */ @Component({ selector: 'toh-heroes', template: `

My Heroes

{{selectedHero.name | uppercase}} is my hero

`, styleUrls: [` .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; } `] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; } ``` ```typescript /* recommended */ @Component({ selector: 'toh-heroes', templateUrl: 'heroes.component.html', styleUrls: ['heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; } ``` Back to top :marked ### Decorate Input and Output Properties Inline #### Style 05-12 - Use [`@Input`](https://angular.io/docs/ts/latest/api/core/Input-var.html) and [`@Output`](https://angular.io/docs/ts/latest/api/core/Output-var.html) instead of the `inputs` and `outputs` properties of the [`@Directive`](https://angular.io/docs/ts/latest/api/core/Directive-decorator.html) and [`@Component`](https://angular.io/docs/ts/latest/api/core/Component-decorator.html) decorators: - Place the `@Input()` or `@Output()` on the same line as the property they decorate. **Why?**: It is easier and more readable to idnetify which properties in a class are inputs or outputs. **Why?**: If we ever need to rename the name of the property, or event name associated to [`@Input`](https://angular.io/docs/ts/latest/api/core/Input-var.html) or respectively [`@Output`](https://angular.io/docs/ts/latest/api/core/Output-var.html) we can modify it on 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 makes for shorter code and still easily identifies the property as an input or output. ```typescript /* avoid */ @Component({ selector: 'toh-button', template: `...`, inputs: [ 'label' ], outputs: [ 'change' ] }) class ButtonComponent { change = new EventEmitter(); label: string; } ``` ```typescript /* recommended */ @Component({ selector: 'toh-button', template: `...` }) class ButtonComponent { @Output() change = new EventEmitter(); @Input() label: string; } ``` Back to top :marked ### Avoid Renaming Inputs and Outputs #### Style 05-13 - Avoid renaming inputs and outputs, when possible. **Why?**: May lead to confusion when the output or the input properties of a given directive are named a given way but exported differently as a public API. ```typescript /* avoid */ @Component({ selector: 'toh-button', template: `...` }) class ButtonComponent { @Output('changeEvent') change = new EventEmitter(); @Input('labelAttribute') label: string; } ``` ```html /* avoid */ ``` ```typescript /* recommended */ @Component({ selector: 'toh-button', template: `...` }) class ButtonComponent { @Output() change = new EventEmitter(); @Input() label: string; } ``` ```html /* recommended */ ``` Back to top :marked ### Member Sequence #### Style 05-14 - Place properties up top followed by methods. - Private members follow public members, alphabetized. **Why?** Placing members in a consistent sequence makes it easy to read and helps you instantly identify which members of the component serve which purpose. ```typescript /* recommended */ export class HeroComponent implements OnInit { // public properties message: string; title: string; // private fields private defaults = { title: '', message: 'May the Force be with You' }; private heroElement: any; // public methods activate(message = this.defaults.message, title = this.defaults.title) { this.title = title; this.message = message; this.show(); } ngOnInit() { this.heroElement = document.getElementById('hero-toast'); } // private methods private hide() { this.heroElement.style.opacity = 0; window.setTimeout(() => this.heroElement.style.zIndex = 0, 400); } private show() { console.log(this.message); this.heroElement.style.opacity = 1; this.heroElement.style.zIndex = 9999; window.setTimeout(() => this.hide(), 2500); } } ``` Back to top :marked ### Defer Logic to Services #### Style 05-15 - Defer logic in a component by delegating to services. - 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. ```typescript // avoid export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private http: Http) { } getHeros() { this.heroes = []; this.http.get(heroesUrl) .map((response: Response) => response.json().data) .catch(this.exceptionService.catchBadResponse) .finally(() => this.spinnerService.hide()) .subscribe(heroes => this.heroes = heroes); } ngOnInit() { this.getHeros(); } } ``` ```typescript // recommended export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private heroService: HeroService) { } getHeros() { this.heroes = []; this.heroService.getHeros() .subscribe(heroes => this.heroes = heroes); } ngOnInit() { this.getHeros(); } } ``` Back to top :marked ### Don't Prefix Output Properties #### Style 05-15 - Name events without the prefix `on`. - Name your 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](https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax) `on-*`. If the event itself was prefixed with `on` this would result in an `on-onEvent` binding expression. ```typescript /* avoid */ @Component(...) export class HeroComponent { @Output() onSavedTheDay = new EventEmitter(); } ``` ```ts /* recommended */ @Component(...) export class HeroComponent { @Output() savedTheDay = new EventEmitter(); } ``` Back to top :marked ### Put Presentation Logic in the Component Class #### Style 05-16 - 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 logic of the components in their controller, instead of template will improve testability, maintability, reusability. ```typescript /* avoid */ @Component({ selector: 'toh-heroes-list', template: `
Your list of heroes: Total powers: {{totalPowers}}
Average power: {{totalPowers / heroes.length}}
` }) export class HeroesListComponent { heroes: Hero[]; totalPowers: number; } ``` ```typescript /* recommended */ @Component({ selector: 'toh-heroes-list', template: `
Your list of heroes: Total powers: {{totalPowers}}
Average power: {{avgPower}}
` }) export class HeroesListComponent { heroes: Hero[]; totalPowers: number; avgPower: number; } ``` Back to top :marked ## Directives ### Use lowerCamelCase for Directive Selectors #### Style 06-01 - Use `lowerCamelCase` for naming the selectors of your directives. **Why?**: Keeps the names of the properties defined in the components that are bound to the view consistent with the attribute names. **Why?**: The Angular 2 HTML parser is case sensitive so `lowerCamelCase` attributes are well supported. - Use custom prefix for the selector of your directives (for instance below is used the prefix `sg` from **S**tyle **G**uide). **Why?**: This way you will be able to prevent name collisions. ```typescript /* avoid */ @Directive({ selector: '[validate]' }) class ValidateDirective {} ``` ```typescript /* recommended */ @Directive({ selector: '[tohValidate]' }) class ValidateDirective {} ``` Back to top :marked ## Services ### Singletons #### Style 07-40 - Services are singletons withint he same injector. They should be used for sharing data and functionality. ```typescript // service import { Injectable } from 'angular2/core'; import { Hero } from './hero'; @Injectable() export class HeroService { getHeroes() { return this.http.get('api/heroes') .map((response: Response) => response.json().data) } } ``` Back to top :marked ### Providing a Service #### Style 07-41 - Services should be provided to the Angular 2 injector at the top-most component where they will be shared. **Why?** The Angular 2 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 and has no state, or state that must be shared. **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. ```typescript /* recommended */ // app.component.ts import { Component } from 'angular2/core'; import { HeroListComponent } from './heroes/hero-list.component'; import { HeroService } from './common/hero.service'; @Component({ selector: 'toh-app', template: ` `, directives: [HeroListComponent], providers: [HeroService] }) export class AppComponent { } ``` ```typescript /* recommended */ // hero-list.component.ts import { Component, OnInit } from 'angular2/core'; import { HeroService } from './common/hero.service'; import { Hero } from './common/hero'; @Component({ selector: 'toh-heroes', template: `
{{heroes | json}}
` }) export class HeroListComponent implements OnInit{ heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } } ``` Back to top :marked ### Single Responsibility #### Style 07-42 - Services should have a [single responsibility](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is encapsulated by its context. Once a service begins to exceed that singular purpose, a new one should be created. Back to top :marked ## Data Services ### Separate Data Calls #### Style 08-50 - Refactor logic for making data operations and interacting with data to a service. 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?** Data service implementation may have very specific code to handle the data repository. This may include headers, how to talk to the data, or other services such as `Http`. Separating the logic into a data service encapsulates this logic in a single place hiding the implementation from the outside consumers (perhaps a component), also making it easier to change the implementation. ```typescript // recommended export class HeroListComponent implements OnInit { heroes: Hero[]; filteredHeros = this.heroes; constructor(private heroService: HeroService) { } getHeros() { this.heroes = []; this.heroService.getHeros() .subscribe(heroes => { this.heroes = this.filteredHeros = heroes; }, error => { console.log('error occurred here'); console.log(error); }, () => { console.log('completed'); }); } ngOnInit() { this.getHeros(); } } ``` Back to top :marked ## Lifecycle Hooks Use Lifecycle Hooks to tap into important events exposed by Angular. Back to top :marked ### Implement Lifecycle Hooks Interfaces #### Style 09-03 - Implement the lifecycle hook interfaces. **Why?**: We will avoid uninteionally not calling the hook if we misspell the method. ```typescript /* avoid */ import {Component} from 'angular2/core'; @Component({ selector: 'toh-button', template: `...` }) class ButtonComponent { onInit() { // mispelled console.log('The component is initialized'); } } ``` ```typescript /* recommended */ import {Component, OnInit} from 'angular2/core'; @Component({ selector: 'toh-button', template: `...` }) class ButtonComponent implements OnInit { ngOnInit() { console.log('The component is initialized'); } } ``` Back to top :marked ## Routing Client-side routing is important for creating a navigation flow between a component tree hierarchy, and composing components that are made of many other child components. Back to top :marked ### Component Router #### Style 10-30 - Separate route configuration into a routing component file, also known as a component router. - Use a `` in the component router, where the routes will have their component targets display their templates. - Focus the logic in the component router to the routing aspects and its target components. Extract other logic to services and other components. **Why?** A component that handles routing is known as the component router, thus this follows the Angular 2 routing pattern. **Why?** A component that handles routing is known as the componenter router. **Why?** The `` indicates where the tempalte should be displayed for the target route. ```typescript import { Component } from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { HeroesComponent, HeroService } from './+heroes'; import { DashboardComponent } from './+dashboard'; import { NavComponent } from './layout/nav.component'; @Component({ selector: 'toh-app', templateUrl: 'app/app.component.html', styleUrls: ['app/app.component.css'], directives: [ROUTER_DIRECTIVES, NavComponent], providers: [ ROUTER_PROVIDERS, HeroService ] }) @RouteConfig([ { path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true }, { path: '/heroes/...', name: 'Heroes', component: HeroesComponent }, ]) export class AppComponent { } ``` Back to top :marked ## Appendix ### File Templates and Snippets 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. ### Visual Studio Code - [Visual Studio Code](https://code.visualstudio.com/) snippets that follow these styles and guidelines. - [Snippets for VS Code](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) [![Use Extension](https://github.com/johnpapa/vscode-angular2-snippets/raw/master/images/use-extension.gif)](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) Back to top