angular-docs-cn/public/docs/ts/latest/guide/style-guide.jade

1089 lines
37 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

include ../_util-fns
:marked
Welcome to the Angular 2 Guide of Style (version 4)
## 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. [Naming](#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)
.l-main-section
:marked
## Single Responsibility
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
<a id="01-01"></a>
#### Style 01-01
.s-rule
:marked
Define one component per file and strive for fewer than 400 lines of code.
.s-why
:marked
**Why?** One component per file makes it far easier to read, maintain, and avoid collisions with teams in source control.
**Why?** One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.
**Why?** A single component can be the default export for its file which facilitates lazy loading with the Component Router.
:marked
The key is to make the code more reusable, easier to read, and less mistake prone.
The following *negative* example defines the `AppComponent`, bootstraps the app, defines the `Hero` model object, and loads heroes from the server ... all in the same file. *Don't do this*.
+makeExample('style-guide/ts/01-01/app/heroes/hero.component.avoid.ts', '', 'hero.component.ts')(avoid=1)
:marked
Better to redistribute the component and supporting activities into their own dedicated files.
+makeTabs(
`style-guide/ts/01-01/app/main.ts,
style-guide/ts/01-01/app/app.component.ts,
style-guide/ts/01-01/app/heroes/heroes.component.ts,
style-guide/ts/01-01/app/heroes/hero.service.ts,
style-guide/ts/01-01/app/heroes/hero.model.ts,
style-guide/ts/01-01/app/heroes/mock-heroes.ts`,
'',
`app/main.ts,
app/app.component.ts,
app/heroes/heroes.component.ts,
app/heroes/hero.service.ts,
app/heroes/hero.model.ts,
app/heroes/mock-heroes.ts`)
:marked
As the app grows, this rule becomes even more important.
a(href="#toc") Back to top
.l-main-section
:marked
### Small Functions
<a id="01-02"></a>
#### 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.
a(href="#toc") Back to top
.l-main-section
:marked
## Naming
Naming conventions are hugely important to maintainbility and readability. This guide will recommend naming conventions for the file name and the symbol name.
.l-main-section
:marked
### General Naming Guidelines
<a id="02-01"></a>
#### 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 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.
a(href="#toc") Back to top
.l-main-section
:marked
### Separate File Names with Dots and Dashes
<a id="02-02"></a>
#### 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 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.
a(href="#toc") Back to top
.l-main-section
:marked
### Components and Directives
<a id="02-03"></a>
#### 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.
**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.
```
/* recommended */
AppComponent // app.component.ts
HeroesComponent // heroes.component.ts
HeroListComponent // hero-list.component.ts
HeroDetailComponent // hero-detail.component.ts
/* recommended */
ValidationDirective // validation.directive.ts
```
a(href="#toc") Back to top
.l-main-section
:marked
### Service Names
<a id="02-04"></a>
#### 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).
**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.
```
HeroDataService // hero-data.service.ts
CreditService // credit.service.ts
LoggerService // logger.service.ts
```
a(href="#toc") Back to top
.l-main-section
:marked
### Bootstrapping
<a id="02-05"></a>
#### 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.
a(href="#toc") Back to top
.l-main-section
:marked
### Use lowerCamelCase for Directive Selectors
<a id="02-06"></a>
#### 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
a(href="#toc") Back to top
.l-main-section
:marked
### Custom Prefix for Components
<a id="02-07"></a>
#### 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.
+makeExample('style-guide/ts/02-07/app/heroes/hero.component.avoid.ts', '', 'hero.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/02-07/app/users/users.component.avoid.ts', '', 'users.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/02-07/app/heroes/hero.component.ts', 'example', 'hero.component.ts')
:marked
+makeExample('style-guide/ts/02-07/app/users/users.component.ts', 'example', 'users.component.ts')
:marked
:marked
### Custom Prefix for Directives
<a id="02-08"></a>
#### 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
+makeExample('style-guide/ts/02-08/app/shared/validate.directive.avoid.ts', '', 'validate.directive.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/02-08/app/shared/validate.directive.ts', 'example', 'validate.directive.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Pipe Names
<a id="02-09"></a>
#### Style 02-09
- Use consistent names for all pipes named after their feature.
**Why?** Provides a consistent way to quickly identify and reference pipes.
```
EllipsisPipe // ellipsis.pipe.ts
InitCapsPipe // init-caps.pipe.ts
```
a(href="#toc") Back to top
.l-main-section
:marked
### Unit Test File Names
<a id="02-10"></a>
#### 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 tests.
**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
```
a(href="#toc") Back to top
.l-main-section
:marked
### End to End Test File Names
<a id="02-11"></a>
#### 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
```
a(href="#toc") Back to top
.l-main-section
:marked
### Route Naming
<a id="02-30"></a>
#### 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.
```
{ path: '/dashboard', name: 'Dashboard', component: DashboardComponent }
```
a(href="#toc") Back to top
.l-main-section
:marked
## Application Structure
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.
a(href="#toc") Back to top
.l-main-section
:marked
### LIFT
<a id="04-01"></a>
#### Style 04-01
- 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 our app structure is to ask ourselves: How quickly can we open and work in all of the related files for a feature?
a(href="#toc") Back to top
.l-main-section
:marked
### Locate
<a id="04-02"></a>
#### Style 04-02
- Make locating our code intuitive, simple and fast.
**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.
a(href="#toc") Back to top
.l-main-section
:marked
### Identify
<a id="04-03"></a>
#### Style 04-03
- When we look at a file we should instantly know what it contains and represents.
**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.
a(href="#toc") Back to top
.l-main-section
:marked
### Flat
<a id="04-04"></a>
#### Style 04-04
- 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. 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.
a(href="#toc") Back to top
.l-main-section
:marked
### T-DRY (Try to Stick to DRY)
<a id="04-05"></a>
#### 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 we call it T-DRY. We dont want to type `hero-view.component.html` for a view because, well, its obviously a view. If it is not obvious or by convention, then we name it.
a(href="#toc") Back to top
.l-main-section
:marked
### Overall Structural Guidelines
<a id="04-50"></a>
#### 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. We didn't write them and we don't want them cluttering our app.
- TODO EXAMPLE
a(href="#toc") Back to top
.l-main-section
:marked
### Layout
<a id="04-51"></a>
#### 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.
a(href="#toc") Back to top
.l-main-section
:marked
### Folders-by-Feature Structure
<a id="04-06"></a>
#### 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. 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.
**Why?** The LIFT guidelines are all covered.
**Why?** Helps reduce the app from becoming cluttered through organizing the content and keeping them aligned with the LIFT guidelines.
**Why?** When there are a lot of files (e.g. 10+) locating them is easier with a consistent folder structures and more difficult in flat structures.
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
```
a(href="#toc") Back to top
.l-main-section
:marked
## Components
### Components Selector Naming
<a id="05-02"></a>
#### Style 05-02
- 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/).
+makeExample('style-guide/ts/05-02/app/heroes/hero-button.component.avoid.ts', '', 'hero-button.component.ts')(avoid=1)
:marked
+makeTabs(
`style-guide/ts/05-02/app/heroes/hero-button.component.ts,
style-guide/ts/05-02/app/app.component.html`,
'example,',
`app/heroes/hero-button.component.ts,
app/app.component.html`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Components as Elements
<a id="05-03"></a>
#### 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.
**Why?**: It is easier to recognize that a symbol is a component vs a directive by looking at the template's html.
+makeExample('style-guide/ts/05-03/app/heroes/hero-button.component.avoid.ts', '', 'hero-button.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-03/app/heroes/hero-button.component.avoid.html', '', 'hero-button.component.html')(avoid=1)
:marked
+makeTabs(
`style-guide/ts/05-03/app/heroes/hero-button.component.ts,
style-guide/ts/05-03/app/app.component.html`,
'example,',
`app/heroes/hero-button.component.ts,
app/app.component.html`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Extract Template and Styles to Their Own Files
<a id="05-04"></a>
#### 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 our component name.
- Name the style file `[component-name].component.css`, where [component-name] is our 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.
+makeExample('style-guide/ts/05-04/app/heroes/heroes.component.avoid.ts', '', 'heroes.component.ts')(avoid=1)
:marked
+makeTabs(
`style-guide/ts/05-04/app/heroes/heroes.component.ts,
style-guide/ts/05-04/app/heroes/heroes.component.html,
style-guide/ts/05-04/app/heroes/heroes.component.css`,
'example,,',
`app/heroes/heroes.component.ts,
app/heroes/heroes.component.html,
app/heroes/heroes.component.css`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Decorate Input and Output Properties Inline
<a id="05-12"></a>
#### 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.
+makeExample('style-guide/ts/05-12/app/heroes/hero-button.component.avoid.ts', '', 'hero-button.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-12/app/heroes/hero-button.component.ts', 'example', 'hero-button.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Avoid Renaming Inputs and Outputs
<a id="05-13"></a>
#### 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.
+makeExample('style-guide/ts/05-13/app/heroes/hero-button.component.avoid.ts', '', 'hero-button.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-13/app/app.component.avoid.html', '', 'app.component.html')(avoid=1)
:marked
+makeTabs(
`style-guide/ts/05-13/app/heroes/hero-button.component.ts,
style-guide/ts/05-13/app/app.component.html`,
'example,',
`app/heroes/hero-button.component.ts,
app/app.component.html`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Member Sequence
<a id="05-14"></a>
#### 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 we instantly identify which members of the component serve which purpose.
+makeExample('style-guide/ts/05-14/app/toast/toast.component.avoid.ts', '', 'toast.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-14/app/toast/toast.component.ts', 'example', 'toast.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Defer Logic to Services
<a id="05-15"></a>
#### 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.
+makeExample('style-guide/ts/05-15/app/heroes/hero-list.component.avoid.ts', '', 'hero-list.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-15/app/heroes/hero-list.component.ts', 'example', 'hero-list.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Don't Prefix Output Properties
<a id="05-16"></a>
#### Style 05-16
- Name events without the prefix `on`.
- Name our 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.
+makeExample('style-guide/ts/05-16/app/heroes/hero.component.avoid.ts', '', 'hero.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-16/app/app.component.avoid.html', '', 'app.component.html')(avoid=1)
:marked
+makeTabs(
`style-guide/ts/05-16/app/heroes/hero.component.ts,
style-guide/ts/05-16/app/app.component.html`,
'example,',
`app/heroes/hero.component.ts,
app/app.component.html`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Put Presentation Logic in the Component Class
<a id="05-17"></a>
#### Style 05-17
- 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.
+makeExample('style-guide/ts/05-17/app/heroes/heroes-list.component.avoid.ts', '', 'heroes-list.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/05-17/app/heroes/heroes-list.component.ts', 'example', 'heroes-list.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
## Directives
- TODO
a(href="#toc") Back to top
.l-main-section
:marked
### Use HostListener and HostBinding Class Decorators
<a id="06-03"></a>
#### Style 06-03
- Use @HostListener and @HostBinding instead of the host property of the @Directive and @Component decorators:
**Why?**: The name of the property, or method name associated to @HostBinding or respectively @HostListener should be modified only in a single place - in the directive's controller. In contrast if we use host we need to modify both the property declaration inside the controller, and the metadata associated to the directive.
**Why?**: The metadata declaration attached to the directive is shorter and thus more readable.
```
/* avoid */
@Directive({
selector: '[tohValidator]',
host: {
'(mouseenter)': 'onMouseEnter()',
'attr.role': 'button'
}
})
export class ValidatorDirective {
role = 'button';
onMouseEnter() {...}
}
```
```
/* recommended */
@Directive({
selector: '[tohValidator]'
})
export class ValidatorDirective {
@HostBinding('attr.role') role = 'button';
@HostListener('mouseenter') onMouseEnter() {...}
}
```
a(href="#toc") Back to top
.l-main-section
:marked
## Services
### Services are Singletons in Same Injector
<a id="07-01"></a>
#### Style 07-01
- Services are singletons within the same injector. Use them for sharing data and functionality.
**Why?:** Services are ideal for sharing methods across a feature area or an app.
**Why?:** Services are ideal for sharing stateful in-memory data.
+makeExample('style-guide/ts/07-01/app/heroes/shared/hero.service.ts', 'example', 'hero.service.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Single Responsibility
<a id="07-02"></a>
#### Style 07-02
- Services should have a single responsibility that is encapsulated by its context. Once a service begins to exceed that singular purpose, a new one should be created.
**Why?:** When a service has multiple responsibilities, it becomes difficult to test.
**Why?:** When a service has multiple responsibilities, every Component or Service that injects it now carries the weight of them all.
a(href="#toc") Back to top
.l-main-section
:marked
### Providing a Service
<a id="07-03"></a>
#### Style 07-03
- 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.
+makeTabs(
`style-guide/ts/07-03/app/app.component.ts,
style-guide/ts/07-03/app/heroes/hero-list.component.ts`,
'',
`app/app.component.ts,
app/heroes/hero-list.component.ts`)
:marked
a(href="#toc") Back to top
.l-main-section
:marked
### Use the @Injectable() Class Decorator
<a id="07-04"></a>
#### Style 07-04
- 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.
+makeExample('style-guide/ts/07-04/app/heroes/hero-arena.service.avoid.ts', '', 'hero-arena.service.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/07-04/app/heroes/hero-arena.service.ts', 'example', 'hero-arena.service.ts')
:marked
a(href="#toc") Back to top
.l-main-section
:marked
## Data Services
### Separate Data Calls
<a id="08-01"></a>
#### 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.
**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.
a(href="#toc") Back to top
.l-main-section
:marked
## Lifecycle Hooks
Use Lifecycle Hooks to tap into important events exposed by Angular.
a(href="#toc") Back to top
.l-main-section
:marked
### Implement Lifecycle Hooks Interfaces
<a id="09-01"></a>
#### Style 09-01
- Implement the lifecycle hook interfaces.
**Why?**: We will avoid unintentionally not calling the hook if we misspell the method.
+makeExample('style-guide/ts/09-01/app/hero-button.component.avoid.ts', '', 'hero-button.component.ts')(avoid=1)
:marked
+makeExample('style-guide/ts/09-01/app/hero-button.component.ts', 'example', 'hero-button.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
: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.
a(href="#toc") Back to top
.l-main-section
:marked
### Component Router
<a id="10-01"></a>
#### Style 10-01
- Separate route configuration into a routing component file, also known as a component router.
- Use a `<router-outlet>` 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 `<router-outlet>` indicates where the tempalte should be displayed for the target route.
+makeExample('style-guide/ts/10-01/app/app.component.ts', '', 'app.component.ts')
:marked
a(href="#toc") Back to top
.l-main-section
: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)
a(href="#toc") Back to top