diff --git a/public/_includes/_util-fns.jade b/public/_includes/_util-fns.jade index d5274d903e..8d7924e76b 100644 --- a/public/_includes/_util-fns.jade +++ b/public/_includes/_util-fns.jade @@ -9,8 +9,13 @@ mixin makeExample(filePath, region, title, stylePatterns) - var frag = getFrag(filePath, region); - var defaultFormat = frag.split('\n').length > 2 ? "linenums" : ""; - var format = attributes.format || defaultFormat; + - var avoid = !!attributes.avoid; + if (title) - .example-title #{title} + if (avoid) + .example-title.avoid AVOID: #{title} + else + .example-title #{title} code-example(language="#{language}" format="#{format}") != styleString(frag, stylePatterns) @@ -37,9 +42,13 @@ mixin makeJson( filePath, jsonConfig, title, stylePatterns) - var frag = getFrag(filePath, ''); - var json = unescapeHtml(frag); - var jsonExtract = extractJson(json, jsonConfig); + - var avoid = !!attributes.avoid; if (title) - .example-title #{title} + if (avoid) + .example-title.avoid #{title} + else + .example-title #{title} code-example(language="#{language}" format="#{format}") if (jsonExtract == 'ERROR') err ERROR: Unable to extract json using config: "#{jsonConfig.toString()}" @@ -303,4 +312,4 @@ script. - } - } - } -- } \ No newline at end of file +- } diff --git a/public/docs/_examples/style-guide/ts/001/app/app.component.ts b/public/docs/_examples/style-guide/ts/01-01/app/app.component.ts similarity index 75% rename from public/docs/_examples/style-guide/ts/001/app/app.component.ts rename to public/docs/_examples/style-guide/ts/01-01/app/app.component.ts index 885ef3a0e6..3a464f3112 100644 --- a/public/docs/_examples/style-guide/ts/001/app/app.component.ts +++ b/public/docs/_examples/style-guide/ts/01-01/app/app.component.ts @@ -10,9 +10,9 @@ import { Hero } from './hero'; import { HeroService } from './hero.service'; @Component({ - selector: 'my-app', + selector: 'toh-app', template: ` -
{{heroes | json}}+
{{heroes | json}}`, styleUrls: ['app/app.component.css'], providers: [HeroService] @@ -20,10 +20,10 @@ import { HeroService } from './hero.service'; export class AppComponent implements OnInit{ heroes: Hero[] = []; - constructor(private _heroService: HeroService) {} + constructor(private heroService: HeroService) {} ngOnInit() { - this._heroService.getHeroes() + this.heroService.getHeroes() .then(heroes => this.heroes = heroes); } } diff --git a/public/docs/_examples/style-guide/ts/001/app/hero.model.ts b/public/docs/_examples/style-guide/ts/01-01/app/hero.model.ts similarity index 100% rename from public/docs/_examples/style-guide/ts/001/app/hero.model.ts rename to public/docs/_examples/style-guide/ts/01-01/app/hero.model.ts diff --git a/public/docs/_examples/style-guide/ts/001/app/hero.service.ts b/public/docs/_examples/style-guide/ts/01-01/app/hero.service.ts similarity index 100% rename from public/docs/_examples/style-guide/ts/001/app/hero.service.ts rename to public/docs/_examples/style-guide/ts/01-01/app/hero.service.ts diff --git a/public/docs/_examples/style-guide/ts/001/app/main.ts b/public/docs/_examples/style-guide/ts/01-01/app/main.ts similarity index 100% rename from public/docs/_examples/style-guide/ts/001/app/main.ts rename to public/docs/_examples/style-guide/ts/01-01/app/main.ts diff --git a/public/docs/_examples/style-guide/ts/001/app/placeholder.ts b/public/docs/_examples/style-guide/ts/01-01/app/placeholder.ts similarity index 81% rename from public/docs/_examples/style-guide/ts/001/app/placeholder.ts rename to public/docs/_examples/style-guide/ts/01-01/app/placeholder.ts index 9c78c378ce..59e5befb52 100644 --- a/public/docs/_examples/style-guide/ts/001/app/placeholder.ts +++ b/public/docs/_examples/style-guide/ts/01-01/app/placeholder.ts @@ -1,6 +1,6 @@ // #docplaster -// #docregion 001-1 +// #docregion 01-01-1 /* avoid */ import { bootstrap } from 'angular2/platform/browser'; import { Component, OnInit } from 'angular2/core'; @@ -9,7 +9,7 @@ selector: 'my-app', template: `
{{heroes | json}}+
{{heroes | json}}`, styleUrls: ['app/app.component.css'] }) @@ -27,11 +27,11 @@ function getHeroes() { return // some promise of data; - } -// #enddocregion 001-1 + } +// #enddocregion 01-01-1 -// #docregion 001-2 +// #docregion 01-01-2 /* recommended */ // main.ts @@ -50,7 +50,7 @@ @Component({ selector: 'my-app', template: ` -
{{heroes | json}}+
{{heroes | json}}`, styleUrls: ['app/app.component.css'], providers: [HeroService] @@ -58,16 +58,16 @@ export class AppComponent implements OnInit{ heroes: Hero[] = []; - constructor(private _heroService: HeroService) {} + constructor(private heroService: HeroService) {} ngOnInit() { - this._heroService.getHeroes() + this.heroService.getHeroes() .then(heroes => this.heroes = heroes); } } -// #enddocregion 001-2 +// #enddocregion 01-01-2 -// #docregion 001-3 +// #docregion 01-01-3 /* recommended */ // hero.service.ts @@ -80,9 +80,9 @@ return Promise.resolve(HEROES); } } -// #enddocregion 001-3 +// #enddocregion 01-01-3 -// #docregion 001-4 +// #docregion 01-01-4 /* recommended */ // hero.ts @@ -90,4 +90,4 @@ id: number; name: string; } -// #enddocregion 001-4 +// #enddocregion 01-01-4 diff --git a/public/docs/ts/latest/guide/style-guide.jade b/public/docs/ts/latest/guide/style-guide.jade index 43a9c89498..ceeac52eb4 100644 --- a/public/docs/ts/latest/guide/style-guide.jade +++ b/public/docs/ts/latest/guide/style-guide.jade @@ -1,21 +1,21 @@ include ../_util-fns :marked - Welcome to the Angular 2 Guide of Style (version 2) - + Welcome to the Angular 2 Guide of Style (version 3) + ## Purpose - If you are looking for an opinionated style guide for syntax, conventions, and structuring Angular applications, then step right in. + If we 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. [Naming](#naming) 1. [Application Structure](#application-structure) 1. [Components](#components) 1. [Directives](#directives) @@ -24,33 +24,38 @@ a(id='toc') 1. [Data Services](#data-services) 1. [Routing](#routing) 1. [Appendix](#appendix) + :marked ## Single Responsibility - ### Rule of 1 + We apply the [Single Responsibility Principle](https:\/\/en.wikipedia.org/wiki/Single_responsibility_principle) to all Components, Services, and other symbols we create. This helps make our app cleaner, easier to read and maintain, and more testable. + + ### Rule of 1 #### Style 01-01 - Define 1 component per file, recommended to be less than 400 lines of code. + - 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 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 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?** 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)') ++makeExample('style-guide/ts/01-01/app/placeholder.ts', '01-01-1', 'app.component.ts (component)')(avoid=1) + :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') + 'style-guide/ts/01-01/app/main.ts,style-guide/ts/01-01/app/app.component.ts,style-guide/ts/01-01/app/hero.service.ts,style-guide/ts/01-01/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. @@ -63,56 +68,66 @@ a(id='toc') - 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 are easier to test, especially when they do one thing and serve one purpose. - **Why?** Small functions promote reuse. + **Why?** Small functions promote reuse. - **Why?** Small functions are easier to read. + **Why?** Small functions are easier to read. - **Why?** Small functions are easier to maintain. + **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. + **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`) + Naming conventions are hugely important to maintainbility and readability. This guide will recommend naming conventions for the file name and the symbol name. + +Back to top + +:marked + ### General Naming Guidelines + + #### Style 02-01 + + - Use consistent names for all symbols following a pattern that describes the symbol's feature then its type. The recommended pattern is `feature.type.ts`. **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?** The naming conventions should simply help we find our 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. - **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 + + #### Style 02-02 - 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. + + - Use conventional suffixes for the types including `*.service.ts`, `*.component.ts`, `*.pipe.ts`. Invent other suffixes where desired for our 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. - +:marked + ### Components and Directives + + #### Style 02-03 + + - 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. @@ -123,7 +138,7 @@ a(id='toc') **Why?** The `Component` suffix is more commonly used and is more explicitly descriptive. - ```typescript + ``` /* recommended */ AppComponent // app.component.ts HeroesComponent // heroes.component.ts @@ -135,10 +150,11 @@ a(id='toc') ``` Back to top + :marked ### Service Names - - #### Style 02-03 + + #### Style 02-04 - 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). @@ -146,171 +162,276 @@ a(id='toc') **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. + **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 - ``` + ``` + HeroDataService // hero-data.service.ts + CreditService // credit.service.ts + LoggerService // logger.service.ts + ``` Back to top + :marked ### Bootstrapping - - #### Style 02-04 + + #### Style 02-05 - 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 + ### Use lowerCamelCase for Directive Selectors + + #### Style 02-06 + + - Use lowerCamelCase for naming the selectors of our 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 2 HTML parser is case sensitive and will recognize lowerCamelCase + +Back to top + +:marked + ### Custom Prefix for Components + + #### Style 02-07 + + - Use a custom prefix for the selector of our components. For example, the prefix `toh` represents from **T**our **o**f **H**eroes and the prefix `admin` represents an admin feature area. + + - Use a prefix that identifies the feature area in the app. + + - In small apps, use a prefix that identifies the app. + + **Why?**: Prevents name collisions + + **Why?**: Our Components and elements are easily identified + + **Why?**: Makes it easier to promoted and share our feature in other apps. + + ``` + /* avoid */ + + // HeroComponent is in the Tour of Heroes feature + @Component({ + selector: 'hero' + }) + export class HeroComponent {} + + // UsersComponent is in an Admin feature + @Component({ + selector: 'users' + }) + export class UsersComponent {} + ``` + + ``` + /* recommended */ + + // HeroComponent is in the Tour of Heroes feature + @Component({ + selector: 'toh-hero' + }) + export class HeroComponent {} + + // UsersComponent is in an Admin feature + @Component({ + selector: 'admin-users' + }) + export class UsersComponent {} + ``` + +:marked + ### Custom Prefix for Directives + + #### Style 02-08 + + - Use a custom prefix for the selector of our directives (for instance below is used the prefix `toh` from **T**our **o**f **H**eroes). + + **Why?**: Prevents name collisions + + **Why?**: Our Directives are easily identified + + ``` + /* avoid */ + @Directive({ + selector: '[validate]' + }) + export class ValidateDirective {} + ``` + + ``` + /* recommended */ + @Directive({ + selector: '[tohValidate]' + }) + export class ValidateDirective {} + ``` + +Back to top + :marked ### Pipe Names - - #### Style 02-10 + + #### Style 02-09 - - Use consistent names for all pipes named after their feature. + - 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 - ``` + ``` + EllipsisPipe // ellipsis.pipe.ts + InitCapsPipe // init-caps.pipe.ts + ``` Back to top + :marked - ### Test File Names - - #### Style 02-12 + ### Unit Test File Names + + #### Style 02-10 - 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 a consistent way to quickly identify tests. **Why?** Provides pattern matching for [karma](http://karma-runner.github.io/) or other test runners. - ``` - // recommended + ``` + // recommended - // Components - heroes.component.spec.ts - hero-list.component.spec.ts - hero-detail.component.spec.ts + // 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 - ``` + // 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 + ### End to End Test File Names + + #### Style 02-11 + + - Name end-to-end test specifications similar to the feature they test with a suffix of `.e2e-spec`. + + **Why?** Provides a consistent way to quickly identify end-to-end tests. + + **Why?** Provides pattern matching for test runners and build automation. + + ``` + // recommended + app.e2e-spec.ts + heroes.e2e-spec.ts + ``` + +Back to top + :marked ### Route Naming - - #### Style 02-31 + + #### Style 02-30 - 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 } - ``` + + ``` + { path: '/dashboard', name: 'Dashboard', component: DashboardComponent } + ``` Back to top + :marked ## Application Structure - TODO - + + Have a near term view of implementation and a long term vision. 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. We didn't write them and we don't want them cluttering our app. Use the naming conventions for file in this guide. + Back to top + :marked ### LIFT - - #### Style 04-40 + + #### Style 04-01 - - 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. + - Structure the app such that we can `L`ocate our code quickly, `I`dentify the code at a glance, keep the `F`lattest structure we 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? + *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 our app structure is to ask ourselves: How quickly can we open and work in all of the related files for a feature? Back to top + :marked ### Locate - - #### Style 04-41 + + #### Style 04-02 - - Make locating your code intuitive, simple and fast. + - Make locating our 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. + **Why?** We find this to be super important for a project. If our team cannot find the files we need to work on quickly, we will not be able to work as efficiently as possible, and the structure needs to change. We 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 + + #### Style 04-03 - - When you look at a file you should instantly know what it contains and represents. + - When we look at a file we 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. + **Why?** We spend less time hunting and pecking for code, and become more efficient. If this means we 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 components, multiple services, or a mixture. + + There are deviations of the 1 per file rule when we have a set of very small features that are all related to each other, as they are still easily identifiable. Back to top + :marked ### Flat - - #### Style 04-43 + + #### Style 04-04 - - Keep a flat folder structure as long as possible. When you get to 7+ files, begin considering separation. + - Keep a flat folder structure as long as possible. When we get to 7+ files, consider 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. + **Why?** Nobody wants to search 7 levels of folders to find a file. 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. We base it on our 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 + + #### Style 04-05 - 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. + **Why?** Being DRY is important, but not crucial if it sacrifices the others in LIFT, which is why we call it T-DRY. We don’t want to type `hero-view.component.html` for a view because, well, it’s obviously a view. If it is not obvious or by convention, then we 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 + + #### Style 04-06 - - 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. + - 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. our 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. @@ -318,11 +439,176 @@ a(id='toc') **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. + **Why?** When there are a lot of files (e.g. 10+) locating them is easier with a consistent folder structures and more difficult in flat structures. - **example coming soon** + Below is an example of a small app. This one is flatter, with fewer folders per component. + + ``` + src/ + app/ + +heroes/ + shared/ + hero.model.ts + hero.service.ts|spec.ts + sort-heroes.pipe.ts|spec.ts + index.ts + hero.component.ts|html|css|spec.ts + hero-list.component.ts|html|css|spec.ts + heroes.component.ts|html|css|spec.ts + index.ts + +villains/ + shared/ + sort-villains.pipe.ts|spec.ts + villain.model.ts + villain.service.ts|spec.ts + index.ts + villain.component.ts|html|css|spec.ts + villain-list.component.ts|html|css|spec.ts + villains.component.ts|html|css|spec.ts + index.ts + assets/ + shared/ + config.ts + exception.service.ts|spec.ts + index.ts + init-caps.pipe.ts|spec.ts + nav.component.ts|html|css|spec.ts + app.component.ts|html|css|spec.ts + main.ts + index.html + tsconfig.json + ``` + + Below is an example of a small app with folders per component. + + ``` + src/ + app/ + +heroes/ + hero/ + hero.component.ts|html|css|spec.ts + index.ts + hero-list/ + hero-list.component.ts|html|css|spec.ts + index.ts + shared/ + hero.model.ts + hero.service.ts|spec.ts + sort-heroes.pipe.ts|spec.ts + index.ts + heroes.component.ts|html|css|spec.ts + index.ts + +villains/ + villain/ + villain.component.ts|html|css|spec.ts + index.ts + villain-list/ + villain-list.component.ts|html|css|spec.ts + index.ts + shared/ + sort-villains.pipe.ts|spec.ts + villain.model.ts + villain.service.ts|spec.ts + index.ts + villains.component.ts|html|css|spec.ts + index.ts + assets/ + shared/ + nav/ + nav.component.ts|html|css|spec.ts + index.ts + config.ts + exception.service.ts|spec.ts + index.ts + init-caps.pipe.ts|spec.ts + app.component.ts|html|css|spec.ts + main.ts + index.html + tsconfig.json + ``` + + Below is an example of a medium app with folders per component. + + ``` + src/ + app/ + +dashboard/ + shared/ + dashboard-button/ + dashboard-button.component.ts|html|css|spec.ts + index.ts + index.ts + dashboard.component.ts|html|css|spec.ts + index.ts + +heroes/ + hero/ + hero.component.ts|html|css|spec.ts + index.ts + hero-list/ + hero-list.component.ts|html|css|spec.ts + index.ts + shared/ + hero-button/ + hero-button.component.ts|html|css|spec.ts + index.ts + hero.service.ts|spec.ts + sort-heroes.pipe.ts|spec.ts + index.ts + heroes.component.ts|html|css|spec.ts + index.ts + +villains/ + villain/ + villain.component.ts|html|css|spec.ts + index.ts + villain-list/ + villain-list.component.ts|html|css|spec.ts + index.ts + shared/ + villain-button/ + villain-button.component.ts|html|css|spec.ts + index.ts + sort-villains.pipe.ts|spec.ts + villain.service.ts|spec.ts + index.ts + villains.component.ts|html|css|spec.ts + index.ts + assets/ + shared/ + filter-text/ + filter-text.component.ts|html|css|spec.ts + filter-text.service.ts|spec.ts + index.ts + modal/ + modal.component.ts|html|css|spec.ts + modal.service.ts|spec.ts + index.ts + nav/ + nav.component.ts|html|css|spec.ts + index.ts + spinner/ + spinner.component.ts|html|css|spec.ts + spinner.service.ts|spec.ts + index.ts + toast/ + toast.component.ts|html|css|spec.ts + toast.service.ts|spec.ts + index.ts + config.ts + data.service.ts|spec.ts + entity.service.ts|spec.ts + exception.service.ts|spec.ts + index.ts + init-caps.pipe.ts|spec.ts + message.service.ts|spec.ts + models.ts + app.component.ts|html|css|spec.ts + main.ts + index.html + tsconfig.json + ``` Back to top + :marked ## Components @@ -330,32 +616,33 @@ a(id='toc') #### Style 05-02 - - Use `kebab-case` for naming the element selectors of your components. + - We use `kebab-case` for naming the element selectors of our 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' + selector: 'tohHeroButton' }) - class HeroButtonComponent {} + export class HeroButtonComponent {} ``` - ```typescript + ``` /* recommended */ @Component({ - selector: 'hero-button' + selector: 'toh-hero-button' }) - class HeroButtonComponent {} + export class HeroButtonComponent {} ``` ```html /* recommended */ -
{{heroes | json}}+
{{heroes | json}}` }) export class HeroListComponent implements OnInit{ @@ -888,22 +1216,48 @@ a(id='toc') } } ``` - + Back to top + :marked - ### Single Responsibility - - #### Style 07-42 + ### Use the @Injectable() Class Decorator + + #### Style 07-04 - - 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. + - Use the `@Injectable` class decorator instead of the `@Inject` parameter decorator when we are using types as tokens for the dependencies of a service. + + **Why?**: The Angular DI mechanism resolves all the dependencies of our services based on their types declared with the services' constructors. + + **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. + + ``` + /* avoid */ + export class HeroArena { + constructor( + @Inject(HeroFactory) private heroFactory: HeroFactory, + @Inject(Http) private http: Http) {} + } + ``` + + ``` + /* recommended */ + @Injectable() + export class HeroArena { + constructor( + private heroFactory: HeroFactory, + private http: Http) {} + } + ``` Back to top + + :marked ## Data Services ### Separate Data Calls - - #### Style 08-50 + + #### Style 08-01 - 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. @@ -913,74 +1267,48 @@ a(id='toc') **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 + + #### Style 09-01 - Implement the lifecycle hook interfaces. - **Why?**: We will avoid uninteionally not calling the hook if we misspell the method. + **Why?**: We will avoid unintentionally not calling the hook if we misspell the method. - ```typescript + ``` /* avoid */ import {Component} from 'angular2/core'; - + @Component({ selector: 'toh-button', - template: `...` + template: `