Show Menu
Cheatography

Angular 2 Essentials May 2016 Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Template

Angular 1
Angular2
ng-click
(click)
ng-hide
[hidden]
ng-class
[ngClass]
ng-model= “model”
([model]) = “model”
brackets
Set value
parent­heses
Get value
Both
Double binding
<div ng-swi­tch­="">
[ngSwitch] =
<div ng-swi­tch­-wh­en=­“">
*ngSwi­tchWhen =
<div ng-swi­tch­-de­fau­lt=­“">
*ngSwi­tch­Default =
<a ng-hre­f="h­ome­Url­"­>Ho­me<­/a>
<a [href]­=“h­ome­Url­"­>Ho­me<­/a>
<a ng-hre­f=“­#ho­me">­Hom­e</­a>
<a [route­rLi­nk]­="['­Hom­e']­"­>Ho­me<­/a>
The * means that Angular will modify the attached element (li) to create a new template

Pipes

Import {Pipe} from “angul­ar2­/core” @Pipe ({
name:”Girl”
}) export class GirlPipe { transf­orm­(user){ return user.g­ender == ‘girl’; } } @Component { pipes: [GirlPipe] }
addGir­l(n­ewG­irl­:Girl) { this.p­ersons = […this.pe­rso­ns,­new­Girl]
Be careful a pipe does NOT check if the array of object got modified.
So if you want to add new elements to your array, it is required to recreate it instead of pushing and removing it:
Yes, you hate it admit it :P (so do I). However this come with a benefit, it makes Angular 2 faster.
Angular 2 is 3X to 5X than Angular 1. Let’s not forget this.
 

Service

Creation
import {Injec­table} from ‘angul­ar2­/core’ @Injec­table export class UserSe­rvice {}
Bootstrap in Root
bootst­rap­(Ap­p,[­Use­rSe­rvice])
Usage
import {UserS­ervice} from “./use­rSe­rvice”; export class App {service; constr­uct­or(­public userSe­rvi­ce:­Use­rSe­rvice) {this.s­ervice = userSe­rvice}}

Directives

 
@Compo­nen­t({­tem­pla­te,­sel­ect­or,­dir­ect­ive­s:[­You­rDi­rec­tiv­eHe­re]})
Angular 1
Angular 2
<temp a=1></­tem­p>
<temp [a]=1> </t­emp>
return {     scope:­’a=1’; }
import {Compo­nent, Input} from “angul­ar2­/core” export class Temp { @Input() a; }

Shadow DOM

Override the global style and affect every elements who has the classes
@Compo­nen­t({­enc­aps­ula­tion: ViewEn­cap­sul­ati­on.None })
Not get affected by the global style and only care about it’s own style
@Compo­nen­t({­enc­aps­ula­tion: ViewEn­cap­sul­ati­on.N­ative })
Same but works with older browsers like IE
@Compo­nen­t({­enc­aps­ula­tion: ViewEn­cap­sul­ati­on.E­mu­lated })
In angular 2 you can set your style in a component with the attribute encaps­ulation

Routing

Angular 1
Angular 2
$location
_router: Router
$route­Params
_route­Par­ams­:Ro­ute­Params
$route­Par­ams.ge­t(‘­par­am1’)
this._­rou­teP­ara­ms.g­et­(‘p­aram1’)
 
$locat­ion.pa­th(­'...')
this._­rou­ter.na­vigate( ['dest­ina­tio­nName', { param1: param1, param2: param2 }] );
<div ng-vie­w>
<ro­ute­r-o­utl­et>­</r­out­er-­out­let>
Declare route (name in Pascal­Case)
@Route­Con­fig([ {path:­'/c­ris­is-­cen­ter', name: 'Crisi­sCe­nter', component: Crisis­Lis­tCo­mpo­nent, useAsD­efault: true} ])
Add a link
<a [route­rLi­nk]­="['­Cri­sis­Cen­ter­']">­Crisis Center­</a>