Style Guide

Welcome to the Angular Style Guide

Purpose

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

Style Vocabulary

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

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

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

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

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

File Structure Conventions

Some code examples display a file that has one or more similarly named companion files. (e.g. hero.component.ts and hero.component.html).

The guideline will use the shortcut hero.component.ts|html|css|spec to represent those various files. Using this shortcut makes this guide's file structures easier to read and more terse.

Table of Contents

  1. Single Responsibility
  2. Naming
  3. Coding Conventions
  4. App Structure and Angular Modules
  5. Components
  6. Directives
  7. Services
  8. Data Services
  9. Lifecycle Hooks
  10. Appendix

Single Responsibility

Apply the Single Responsibility Principle to all components, services, and other symbols. This helps make the app cleaner, easier to read and maintain, and more testable.

Rule of One

Style 01-01

Do define one thing (e.g. service or component) per file.

Consider limiting files to 400 lines of code.

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

Why? One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

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

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

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

app/heroes/hero.component.ts

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

Better to redistribute the component and supporting activities into their own dedicated files.

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

As the app grows, this rule becomes even more important.

Back to top

Small Functions

Style 01-02

Do define small functions

Consider limiting to no more than 75 lines.

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

Why? Small functions promote reuse.

Why? Small functions are easier to read.

Why? Small functions are easier to maintain.

Why? Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.

Back to top

Naming

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

General Naming Guidelines

Style 02-01

Do use consistent names for all symbols.

Do follow 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 find desited code faster and make it easier to understand.

Why? Names of folders and files should clearly convey their intent. For example, app/heroes/hero-list.component.ts may contain a component that manages a list of heroes.

Back to top

Separate File Names with Dots and Dashes

Style 02-02

Do use dashes to separate words in the descriptive name.

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

Do use consistent type names for all components following a pattern that describes the component's feature then its type. A recommended pattern is feature.type.ts.

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

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

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

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

Why? Provides pattern matching for any automated tasks.

Back to top

Symbols and File Names

Style 02-03

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

Do use upper camel case for class names. Match the name of the symbol to the name of the file.

Do append the symbol name with the conventional suffix for a thing of that type (e.g., Component, Directive, Module, Pipe, Service).

Do give the filename the conventional suffix for a file of that type (e.g., .component.ts, .directive.ts, .module.ts, .pipe.ts, .service.ts).

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

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

Symbol NameFile Name
@Component({ ... }) export class AppComponent { }

app.component.ts

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

heroes.component.ts

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

hero-list.component.ts

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

hero-detail.component.ts

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

validation.directive.ts

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

app.module.ts

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

init-caps.pipe.ts

@Injectable() export class UserProfileService { }

user-profile.service.ts

Back to top

Service Names

Style 02-04

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

Do use upper camel case for services.

Do 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.

Symbol NameFile Name
@Injectable() export class HeroDataService { }

hero-data.service.ts

@Injectable() export class CreditService { }

credit.service.ts

@Injectable() export class Logger { }

logger.service.ts

Back to top

Bootstrapping

Style 02-05

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

Do include error handling in the bootstrapping logic.

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

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

Why? Follows a familiar convention from other technology platforms.

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .then(success => console.log(`Bootstrap success`)) .catch(err => console.error(err));
Back to top

Directive Selectors

Style 02-06

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

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

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

Back to top

Custom Prefix for Components

Style 02-07

Do use a hyphenated, lowercase element selector value (e.g. admin-users).

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

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

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

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

Why? Components are easy to identify in the DOM.

app/heroes/hero.component.ts

/* avoid */ // HeroComponent is in the Tour of Heroes feature @Component({ selector: 'hero' }) export class HeroComponent {}

app/users/users.component.ts

/* avoid */ // UsersComponent is in an Admin feature @Component({ selector: 'users' }) export class UsersComponent {}

app/heroes/hero.component.ts

@Component({ selector: 'toh-hero' }) export class HeroComponent {}

app/users/users.component.ts

@Component({ selector: 'admin-users' }) export class UsersComponent {}

Custom Prefix for Directives

Style 02-08

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

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

Why? Prevents name collisions.

Why? Directives are easily identified.

app/shared/validate.directive.ts

/* avoid */ @Directive({ selector: '[validate]' }) export class ValidateDirective {}

app/shared/validate.directive.ts

@Directive({ selector: '[tohValidate]' }) export class ValidateDirective {}
Back to top

Pipe Names

Style 02-09

Do use consistent names for all pipes, named after their feature.

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

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

ellipsis.pipe.ts

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

init-caps.pipe.ts

Back to top

Unit Test File Names

Style 02-10

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

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

Why? Provides a consistent way to quickly identify tests.

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

Symbol NameFile Name

Components

heroes.component.spec.ts

hero-list.component.spec.ts

hero-detail.component.spec.ts

Services

logger.service.spec.ts

hero.service.spec.ts

filter-text.service.spec.ts

Pipes

ellipsis.pipe.spec.ts

init-caps.pipe.spec.ts

Back to top

End to End Test File Names

Style 02-11

Do name end-to-end test specification files after 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.

Symbol NameFile Name

End to End Tests

app.e2e-spec.ts

heroes.e2e-spec.ts

Back to top

Angular NgModule Names

Style 02-12

Do append the symbol name with the suffix Module.

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

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

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

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

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

Do suffix a RoutingModule class name with RoutingModule.

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

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

Symbol NameFile Name
@NgModule({ ... }) export class AppModule { }

app.module.ts

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

heroes.module.ts

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

villains.module.ts

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

app-routing.module.ts

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

heroes-routing.module.ts

Back to top

Coding Conventions

Have consistent set of coding, naming, and whitespace conventions.

Classes

Style 03-01

Do use upper camel case when naming classes.

Why? Follows conventional thinking for class names.

Why? Classes can be instantiated and construct an instance. By convention, upper camel case indicates a constructable asset.

app/shared/exception.service.ts

/* avoid */ export class exceptionService { constructor() { } }

app/shared/exception.service.ts

export class ExceptionService { constructor() { } }
Back to top

Constants

Style 03-02

Do declare variables with const if their values should not change during the application lifetime.

Why? Conveys to readers that the value is invariant.

Why? TypeScript helps enforce that intent by requiring immediate initialization and by preventing subsequent re-assignment.

Consider spelling const variables in lower camel case.

Why? lower camel case variable names (heroRoutes) are easier to read and understand than the traditional UPPER_SNAKE_CASE names (HERO_ROUTES).

Why? The tradition of naming constants in UPPER_SNAKE_CASE reflects an era before the modern IDEs that quickly reveal the const declaration. TypeScript itself prevents accidental reassignment.

Do tolerate existing const variables that are spelled in UPPER_SNAKE_CASE.

Why? The tradition of UPPER_SNAKE_CASE remains popular and pervasive, especially in third party modules. It is rarely worth the effort to change them or the risk of breaking existing code and documentation.

app/shared/data.service.ts

export const mockHeroes = ['Sam', 'Jill']; // prefer export const heroesUrl = 'api/heroes'; // prefer export const VILLAINS_URL = 'api/villains'; // tolerate
Back to top

Interfaces

Style 03-03

Do name an interface using upper camel case.

Consider naming an interface without an I prefix.

Consider using a class instead of an interface.

Why? TypeScript guidelines discourage the "I" prefix.

Why? A class alone is less code than a class-plus-interface.

Why? A class can act as an interface (use implements instead of extends).

Why? An interface-class can be a provider lookup token in Angular dependency injection.

app/shared/hero-collector.service.ts

/* avoid */ import { Injectable } from '@angular/core'; import { IHero } from './hero.model.avoid'; @Injectable() export class HeroCollectorService { hero: IHero; constructor() { } }

app/shared/hero-collector.service.ts

import { Injectable } from '@angular/core'; import { Hero } from './hero.model'; @Injectable() export class HeroCollectorService { hero: Hero; constructor() { } }
Back to top

Properties and Methods

Style 03-04

Do use lower camel case to name properties and methods.

Avoid prefixing private properties and methods with an underscore.

Why? Follows conventional thinking for properties and methods.

Why? JavaScript lacks a true private property or method.

Why? TypeScript tooling makes it easy to identify private vs public properties and methods.

app/shared/toast.service.ts

/* avoid */ import { Injectable } from '@angular/core'; @Injectable() export class ToastService { message: string; private _toastCount: number; hide() { this._toastCount--; this._log(); } show() { this._toastCount++; this._log(); } private _log() { console.log(this.message); } }

app/shared/toast.service.ts

import { Injectable } from '@angular/core'; @Injectable() export class ToastService { message: string; private toastCount: number; hide() { this.toastCount--; this.log(); } show() { this.toastCount++; this.log(); } private log() { console.log(this.message); } }
Back to top

Import Line Spacing

Style 03-06

Consider leaving one empty line between third party imports and application imports.

Consider listing import lines alphabetized by the module.

Consider listing destructured imported assets alphabetically.

Why? The empty line makes it easy to read and locate imports.

Why? Alphabetizing makes it easier to read and locate imports.

app/heroes/shared/hero.service.ts

/* avoid */ import { ExceptionService, SpinnerService, ToastService } from '../../core'; import { Http, Response } from '@angular/http'; import { Injectable } from '@angular/core'; import { Hero } from './hero.model';

app/heroes/shared/hero.service.ts

import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Hero } from './hero.model'; import { ExceptionService, SpinnerService, ToastService } from '../../core';
Back to top

App Structure and Angular Modules

Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road.

All of the app's code goes in a folder named app. All feature areas are in their own folder, with their own Angular module.

All content is 1 asset per file. Each component, service, and pipe is in its own file. All 3rd party vendor scripts are stored in another folder and not in the app folder. You didn't write them and you don't want them cluttering app. Use the naming conventions for files in this guide.

Back to top

LIFT

Style 04-01

Do structure the app such that you can Locate code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to be DRY.

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

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

Back to top

Locate

Style 04-02

Do make locating code intuitive, simple and fast.

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

Back to top

Identify

Style 04-03

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

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

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

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

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

Back to top

Flat

Style 04-04

Do keep a flat folder structure as long as possible.

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

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

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

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

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

Back to top

T-DRY (Try to be DRY)

Style 04-05

Do be DRY (Don't Repeat Yourself)

Avoid being so DRY that you sacrifice readability.

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

Back to top

Overall Structural Guidelines

Style 04-06

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

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

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

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

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

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

Here is a compliant folder and file structure

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

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

Back to top

Folders-by-Feature Structure

Style 04-07

Do create folders named for the feature area they represent.

Why? A developer can locate the code, identify what each file represents at a glance, the structure is as flat as it can be, and there 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 structure and more difficult in a flat structure.

Do create an Angular module for each feature area.

Why? Angular modules make it easy to lazy load routable features.

Why? Angular modules make it easier to isolate, test, and re-use features.

Refer here to this Folder and File Structure example
Back to top

App Root Module

Style 04-08

Do create an Angular module in the app's root folder (e.g., in /app).

Why? Every app requires at least one root Angular module.

Consider naming the root module app.module.ts.

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

app/app.module.ts

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; @NgModule({ imports: [ BrowserModule, ], declarations: [ AppComponent, HeroesComponent ], exports: [ AppComponent ], entryComponents: [ AppComponent ] }) export class AppModule {}
Back to top

Feature Modules

Style 04-09

Do create an Angular module for all distinct features in an application (e.g. Heroes feature).

Do place the feature module in the same named folder as the feature area (.e.g app/heroes).

Do name the feature module file reflecting the name of the feature area and folder (e.g. app/heroes/heroes.module.ts)

Do name the feature module symbol reflecting the name of the feature area, folder, and file (e.g. app/heroes/heroes.module.ts defines HeroesModule)

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

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

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

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

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

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

Back to top

Shared Feature Module

Style 04-10

Do create a feature module named SharedModule in a shared folder (e.g. app/shared/shared.module.ts defines SharedModule).

Do put common components, directives and pipes that will be used throughout the application by other feature modules in the SharedModule, where those assets are expected to share a new instance of themselves (not singletons).

Do import all modules required by the assets in the SharedModule (e.g. CommonModule and FormsModule).

Why? SharedModule will contain components, directives and pipes that may need features from another common module (e.g. ngFor in CommonModule).

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

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

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

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

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

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

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

Core Feature Module

Style 04-11

Do collect single-use classes and hiding their gory details inside CoreModule. A simplified root AppModule imports CoreModule in its capacity as orchestrator of the application as a whole.

Do create a feature module named CoreModule in a core folder (e.g. app/core/core.module.ts defines CoreModule).

Do put a singleton service whose instance wil be shared throughout the application in the CoreModule (e.g. ExceptionService and LoggerService).

Do import all modules required by the assets in the CoreModule (e.g. CommonModule and FormsModule).

Why? CoreModule provides one or more singleton services. Angular registers the providers with the app root injector, making a singleton instance of each service available to any component that needs them, whether that component is eagerly or lazily loaded.

Why? CoreModule will contain singleton services. When a lazy loaded module imports these, it will get a new instance and not the intended app-wide singleton.

Do gather application-wide, single use components in the CoreModule. Import it once (in the AppModule) when the app starts and never import it anywhere else. (e.g. NavComponent and SpinnerComponent).

Why? Real world apps can have several single-use components (e.g., spinners, message toasts, and modal dialogs) that appear only in the AppComponent template. They are not imported elsewhere so they're not shared in that sense. Yet they're too big and messy to leave loose in the root folder.

Avoid importing the CoreModule anywhere except in the AppModule.

Why? A lazily loaded feature module that directly imports the CoreModule will make its own copy of services and likely have undesireable results.

Why? An eagerly loaded feature module already has access to the AppModule's injector, and thus the CoreModule's services.

Do export all symbols that from the CoreModule that the AppModule will import and make available for other feature modules to use.

Why? CoreModule exists to make commonly used singleton services available for use in the many other modules.

Why? You want the entire app to use the one, singleton instance. You don't want each module to have its own separate instance of singleton services. Yet there is a real danger of that happening accidentally if the CoreModule provides a service.

src
app
core
core.module.ts
logger.service.ts|spec.ts
nav
nav.component.ts|html|css|spec.ts
spinner
spinner.component.ts|html|css|spec.ts
spinner.service.ts|spec.ts
app.component.ts|html|css|spec.ts
app.module.ts
app-routing.module.ts
main.ts
index.html
...
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { HeroesComponent } from './heroes/heroes.component'; import { CoreModule } from './core/core.module'; @NgModule({ imports: [ BrowserModule, CoreModule, ], declarations: [ AppComponent, HeroesComponent ], exports: [ AppComponent ], entryComponents: [ AppComponent ] }) export class AppModule {} import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoggerService } from './logger.service'; import { NavComponent } from './nav/nav.component'; import { SpinnerComponent } from './spinner/spinner.component'; import { SpinnerService } from './spinner/spinner.service'; @NgModule({ imports: [ CommonModule // we use ngFor ], exports: [NavComponent, SpinnerComponent], declarations: [NavComponent, SpinnerComponent], providers: [LoggerService, SpinnerService] }) export class CoreModule { } import { Injectable } from '@angular/core'; @Injectable() export class LoggerService { log(msg: string) { console.log(msg); } error(msg: string) { console.error(msg); } } import { Component, OnInit } from '@angular/core'; @Component({ moduleId: module.id, selector: 'toh-nav', templateUrl: 'nav.component.html', styleUrls: ['nav.component.css'], }) export class NavComponent implements OnInit { menuItems = [ 'Heroes', 'Villains', 'Other' ]; ngOnInit() { } constructor() { } } <header> <div> <h4>Tour of Heroes</h4> </div> <nav> <ul> <li *ngFor="let item of menuItems"> {{item}} </li> </ul> </nav> <br/> </header> import { Component, OnDestroy, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { LoggerService } from '../logger.service'; import { SpinnerState, SpinnerService } from './spinner.service'; @Component({ moduleId: module.id, selector: 'toh-spinner', templateUrl: 'spinner.component.html', styleUrls: ['spinner.component.css'] }) export class SpinnerComponent implements OnDestroy, OnInit { visible = false; private spinnerStateChanged: Subscription; constructor( private loggerService: LoggerService, private spinnerService: SpinnerService ) { } ngOnInit() { console.log(this.visible); this.spinnerStateChanged = this.spinnerService.spinnerState .subscribe((state: SpinnerState) => { this.visible = state.show; this.loggerService.log(`visible=${this.visible}`); }); } ngOnDestroy() { this.spinnerStateChanged.unsubscribe(); } } <div class="spinner" [class.spinner-hidden]="!visible"> </div> import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; export interface SpinnerState { show: boolean; } @Injectable() export class SpinnerService { private spinnerSubject = new Subject<SpinnerState>(); spinnerState = this.spinnerSubject.asObservable(); constructor() { } show() { this.spinnerSubject.next(<SpinnerState>{ show: true }); } hide() { this.spinnerSubject.next(<SpinnerState>{ show: false }); } }

AppModule is a little smaller because many app/root classes have moved to other modules. AppModule is stable because you will add future components and providers to other modules, not this one. AppModule delegates to imported modules rather than doing work. AppModule is focused on its main task, orchestrating the app as a whole.

Back to top

Prevent Reimport of Core Module

Style 04-12

Only the root AppModule should import the CoreModule.

Do guard against reimporting of CoreModule and fail fast by adding guard logic.

Why? Guards against reimporting of the CoreModule.

Why? Guards against creating multiple instances of assets intended to be singletons.

export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) { if (parentModule) { throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`); } } import { NgModule, Optional, SkipSelf } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoggerService } from './logger.service'; import { NavComponent } from './nav/nav.component'; import { throwIfAlreadyLoaded } from './module-import-guard'; @NgModule({ imports: [ CommonModule // we use ngFor ], exports: [NavComponent], declarations: [NavComponent], providers: [LoggerService] }) export class CoreModule { constructor( @Optional() @SkipSelf() parentModule: CoreModule) { throwIfAlreadyLoaded(parentModule, 'CoreModule'); } } Back to top

Lazy Loaded Folders

Style 04-13

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

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

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

Back to top

Never Directly Import Lazy Loaded Folders

Style 04-14

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

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

Back to top

Components

Component Selector Naming

Style 05-02

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

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

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: 'tohHeroButton', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {}
@Component({ selector: 'toh-hero-button', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {} <toh-hero-button></toh-hero-button> Back to top

Components as Elements

Style 05-03

Do 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? A component represents a visual element on the page. Defining the selector as an HTML element tag is consistent with native HTML elements and WebComponents.

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

app/heroes/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: '[tohHeroButton]', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {}

app/app.component.html

<!-- avoid --> <div tohHeroButton></div>
@Component({ selector: 'toh-hero-button', templateUrl: 'hero-button.component.html' }) export class HeroButtonComponent {} <toh-hero-button></toh-hero-button> Back to top

Extract Template and Styles to Their Own Files

Style 05-04

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

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

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

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.

app/heroes/heroes.component.ts

/* avoid */ @Component({ selector: 'toh-heroes', template: ` <div> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{selectedHero.name | uppercase}} is my hero</h2> </div> </div> `, 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; ngOnInit() {} }
@Component({ selector: 'toh-heroes', templateUrl: 'heroes.component.html', styleUrls: ['heroes.component.css'] }) export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; ngOnInit() { } } <div> <h2>My Heroes</h2> <ul class="heroes"> <li *ngFor="let hero of heroes"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <div *ngIf="selectedHero"> <h2>{{selectedHero.name | uppercase}} is my hero</h2> </div> </div> .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; } Back to top

Decorate Input and Output Properties Inline

Style 05-12

Do use @Input and @Output instead of the inputs and outputs properties of the @Directive and @Component decorators:

Do place the @Input() or @Output() on the same line as the property they decorate.

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

Why? If you ever need to rename the property or event name associated with @Input or @Output, you can modify it 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.

app/heroes/shared/hero-button/hero-button.component.ts

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

app/heroes/shared/hero-button/hero-button.component.ts

@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output() change = new EventEmitter<any>(); @Input() label: string; }
Back to top

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.

app/heroes/shared/hero-button/hero-button.component.ts

/* avoid */ @Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output('changeEvent') change = new EventEmitter<any>(); @Input('labelAttribute') label: string; }

app/app.component.html

<!-- avoid --> <toh-hero-button labelAttribute="OK" (changeEvent)="doSomething()"> </toh-hero-button>
@Component({ selector: 'toh-hero-button', template: `<button>{{label}}</button>` }) export class HeroButtonComponent { @Output() change = new EventEmitter<any>(); @Input() label: string; } <toh-hero-button label="OK" (change)="doSomething()"> </toh-hero-button> Back to top

Member Sequence

Style 05-14

Do place properties up top followed by methods.

Do place private members after public members, alphabetized.

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

app/shared/toast/toast.component.ts

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

app/shared/toast/toast.component.ts

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

Put Logic in Services

Style 05-15

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

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

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

Why? Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked.

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

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

app/heroes/hero-list/hero-list.component.ts

/* avoid */ import { OnInit } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Hero } from '../shared/hero.model'; const heroesUrl = 'http://angular.io'; export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private http: Http) {} getHeroes() { this.heroes = []; this.http.get(heroesUrl) .map((response: Response) => <Hero[]>response.json().data) .catch(this.catchBadResponse) .finally(() => this.hideSpinner()) .subscribe((heroes: Hero[]) => this.heroes = heroes); } ngOnInit() { this.getHeroes(); } private catchBadResponse(err: any, source: Observable<any>) { // log and handle the exception return new Observable(); } private hideSpinner() { // hide the spinner } }

app/heroes/hero-list/hero-list.component.ts

import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from '../shared'; @Component({ selector: 'toh-hero-list', template: `...` }) export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private heroService: HeroService) {} getHeroes() { this.heroes = []; this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } ngOnInit() { this.getHeroes(); } }
Back to top

Don't Prefix Output Properties

Style 05-16

Do name events without the prefix on.

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

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

Why? Angular allows for an alternative syntax on-*. If the event itself was prefixed with on this would result in an on-onEvent binding expression.

app/heroes/hero.component.ts

/* avoid */ @Component({ selector: 'toh-hero', template: `...` }) export class HeroComponent { @Output() onSavedTheDay = new EventEmitter<boolean>(); }

app/app.component.html

<!-- avoid --> <toh-hero (onSavedTheDay)="onSavedTheDay($event)"></toh-hero>
export class HeroComponent { @Output() savedTheDay = new EventEmitter<boolean>(); } <toh-hero (savedTheDay)="onSavedTheDay($event)"></toh-hero> Back to top

Put Presentation Logic in the Component Class

Style 05-17

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

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

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

app/heroes/hero-list/hero-list.component.ts

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

app/heroes/hero-list/hero-list.component.ts

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

Directives

Back to top

Use Directives to Enhance an Existing Element

Style 06-01

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

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

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

app/shared/highlight.directive.ts

@Directive({ selector: '[tohHighlight]' }) export class HighlightDirective { @HostListener('mouseover') onMouseEnter() { // do highlight work } }

app/app.component.html

<div tohHighlight>Bombasta</div>
Back to top

Use HostListener and HostBinding Class Decorators

Style 06-03

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

Do be consistent in your choice.

Why? The property associated with @HostBinding or the method associated with @HostListener can be modified only in a single place - in the directive's class. If you use the host metadata property, you must modify both the property declaration inside the controller, and the metadata associated with the directive.

app/shared/validator.directive.ts

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

Compare with the less preferred host metadata alternative.

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

app/shared/validator2.directive.ts

import { Directive } from '@angular/core'; @Directive({ selector: '[tohValidator2]', host: { 'attr.role': 'button', '(mouseenter)': 'onMouseEnter()' } }) export class Validator2Directive { role = 'button'; onMouseEnter() { // do work } }
Back to top

Services

Services are Singletons within an Injector

Style 07-01

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

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

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

app/heroes/shared/hero.service.ts

export class HeroService { constructor(private http: Http) { } getHeroes() { return this.http.get('api/heroes') .map((response: Response) => <Hero[]>response.json().data); } }
Back to top

Single Responsibility

Style 07-02

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

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

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

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

Back to top

Providing a Service

Style 07-03

Do provide services to the Angular injector at the top-most component where they will be shared.

Why? The Angular injector is hierarchical.

Why? When providing the service to a top level component, that instance is shared and available to all child components of that top level component.

Why? This is ideal when a service is sharing methods or state.

Why? This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance.

import { Component } from '@angular/core'; import { HeroService } from './heroes'; @Component({ selector: 'toh-app', template: ` <toh-heroes></toh-heroes> `, providers: [HeroService] }) export class AppComponent {} import { Component, OnInit } from '@angular/core'; import { Hero, HeroService } from '../shared'; @Component({ selector: 'toh-heroes', template: ` <pre>{{heroes | json}}</pre> ` }) export class HeroListComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) { } ngOnInit() { this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes); } } Back to top

Use the @Injectable() Class Decorator

Style 07-04

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

Why? The Angular DI mechanism resolves all dependencies of 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.

app/heroes/shared/hero-arena.service.ts

/* avoid */ export class HeroArena { constructor( @Inject(HeroService) private heroService: HeroService, @Inject(Http) private http: Http) {} }

app/heroes/shared/hero-arena.service.ts

@Injectable() export class HeroArena { constructor( private heroService: HeroService, private http: Http) {} }
Back to top

Data Services

Separate Data Calls

Style 08-01

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

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

Why? The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view.

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

Why? 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.

Back to top

Lifecycle Hooks

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

Back to top

Implement Lifecycle Hooks Interfaces

Style 09-01

Do implement the lifecycle hook interfaces.

Why? Strongly-typed method signatures. The compiler and editor can call out misspellings.

app/heroes/shared/hero-button/hero-button.component.ts

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

app/heroes/shared/hero-button/hero-button.component.ts

@Component({ selector: 'toh-hero-button', template: `<button>OK</button>` }) export class HeroButtonComponent implements OnInit { ngOnInit() { console.log('The component is initialized'); } }
Back to top

Appendix

Useful tools and tips for Angular.

Back to top

Codelyzer

Style A-01

Do use codelyzer to follow this guide.

Consider adjusting the rules in codelyzer to suit your needs.

Back to top

File Templates and Snippets

Style A-02

Do use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs.

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

Use Extension

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

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

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

Back to top