You are on page 1of 14

11/20/2016 Angular 

1 to 2 Quick Reference ­ ts ­ COOKBOOK

ANGULAR 1 TO 2 QUICK REFERENCE

Learn how Angular 1 concepts and techniques map to Angular 2

There are many conceptual and syntactical differences between Angular 1 and Angular 2. This page provides a quick guide to
some common Angular 1 syntax and its equivalent in Angular 2.

See the Angular 2 syntax in this live example.

Contents
This page covers:

Template basics - binding and local variables.

Template directives - built-in directives ngIf and ngClass .

Filters/pipes - built-in lters, known as pipes in Angular 2.

Modules/controllers/components - modules in Angular 2 are slightly different from modules in Angular 1, and controllers are
components in Angular 2.

Style sheets - more options for CSS than in Angular 1.

Template basics
Templates are the user-facing part of an Angular application and are written in HTML. The following table lists some of the key
Angular 1 template features with their equivalent Angular 2 template syntax.

Angular 1 Angular 2

Bindings/interpolation Bindings/interpolation

Your favorite hero is: Your favorite hero is: {{favoriteHero}}


{{vm.favoriteHero}}

In Angular 1, an expression in curly braces denotes one- In Angular 2, a template expression in curly braces still
way binding. This binds the value of the element to a denotes one-way binding. This binds the value of the
property in the controller associated with this template. element to a property of the component. The context of

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 1/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

When using the controller as syntax, the binding is the binding is implied and is always the associated
pre xed with the controller alias ( vm or $ctrl ) component, so it needs no reference variable.
because you have to be speci c about the source of
the binding. For more information, see the Interpolation section of
the Template Syntax page.

Filters Pipes

<td>{{movie.title | uppercase}}</td> <td>{{movie.title | uppercase}}</td>

To lter output in Angular 1 templates, use the pipe


character (|) and one or more lters. In Angular 2 you use similar syntax with the pipe (|)
character to lter output, but now you call them pipes.
This example lters the title property to uppercase. Many (but not all) of the built-in lters from Angular 1
are built-in pipes in Angular 2.

For more information, see the heading Filters/pipes


below.

Local variables Input variables

<tr ng-repeat="movie in vm.movies"> <tr *ngFor="let movie of movies">


<td>{{movie.title}}</td> <td>{{movie.title}}</td>
</tr> </tr>

Here, movie is a user-de ned local variable.


Angular 2 has true template input variables that are
explicitly de ned using the let keyword.

For more information, see the ngFor micro-syntax


section of the Template Syntax page.

Back to top

Template directives
Angular 1 provides more than seventy built-in directives for templates. Many of them aren't needed in Angular 2 because of its
more capable and expressive binding system. The following are some of the key Angular 1 built-in directives and their equivalents
in Angular 2.

Angular 1 Angular 2

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 2/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

ng-app Bootstrapping

<body ng-app="movieHunter"> main.ts

The application startup process is called import { platformBrowserDynamic } from

bootstrapping. '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';

Although you can bootstrap an Angular 1 app in


platformBrowserDynamic().bootstrapModule(AppModule);
code, many applications bootstrap declaratively
with the ng-app directive, giving it the name of
the application's module ( movieHunter ).
app.module.ts

import { NgModule } from '@angular/core';


import { BrowserModule } from '@angular/platform-
browser';

import { AppComponent } from './app.component';

@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Angular 2 doesn't have a bootstrap directive. To launch the app in


code, explicitly bootstrap the application's root module ( AppModule
) in main.ts and the application's root component (
AppComponent ) in app.module.ts .

For more information see Quick Start.

ng-class ngClass

<div ng-class="{active: isActive}"> <div [ngClass]="{active: isActive}">


<div ng-class="{active: isActive, <div [ngClass]="{active: isActive,
shazam: shazam: isImportant}">
isImportant}"> <div [class.active]="isActive">

In Angular 1, the ng-class directive


includes/excludes CSS classes based on an In Angular 2, the ngClass directive works similarly. It
expression. That expression is often a key-value includes/excludes CSS classes based on an expression.
control object with each key of the object de ned
as a CSS class name, and each value de ned as In the rst example, the active class is applied to the element if

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 3/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

a template expression that evaluates to a isActive is true.


Boolean value.
You can specify multiple classes, as shown in the second example.
In the rst example, the active class is applied
to the element if isActive is true. Angular 2 also has class binding, which is a good way to add or
remove a single class, as shown in the third example.
You can specify multiple classes, as shown in the
second example. For more information see the Attribute, Class, and Style Bindings
section of the Template Syntax page.

ng-click bind to the click event

<button ng-click="vm.toggleImage()"> <button (click)="toggleImage()">


<button ng- <button (click)="toggleImage($event)">
click="vm.toggleImage($event)">

In Angular 1, the ng-click directive allows you Angular 1 event-based directives do not exist in Angular 2. Rather,
to specify custom behavior when an element is de ne one-way binding from the template view to the component
clicked. using event binding.

In the rst example, when the user clicks the For event binding, de ne the name of the target event within
button, the toggleImage() method in the parenthesis and specify a template statement, in quotes, to the right
controller referenced by the vm of the equals. Angular 2 then sets up an event handler for the target
controller as alias is executed. event. When the event is raised, the handler executes the template
statement.
The second example demonstrates passing in
the $event object, which provides details about In the rst example, when a user clicks the button, the
the event to the controller. toggleImage() method in the associated component is executed.

The second example demonstrates passing in the $event object,


which provides details about the event to the component.

For a list of DOM events, see: https://developer.mozilla.org/en-


US/docs/Web/Events.

For more information, see the Event Binding section of the Template
Syntax page.

ng-controller Component decorator

<div ng-controller="MovieListCtrl as
vm">

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 4/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

In Angular 1, the ng-controller directive @Component({

attaches a controller to the view. Using the moduleId: module.id,


selector: 'movie-list',
ng-controller (or de ning the controller as
templateUrl: 'movie-list.component.html',
part of the routing) ties the view to the controller
styleUrls: [ 'movie-list.component.css' ],
code associated with that view. })

In Angular 2, the template no longer speci es its associated


controller. Rather, the component speci es its associated template
as part of the component class decorator.

For more information, see Architecture Overview.

ng-hide bind to the hidden property


In Angular 1, the ng-hide directive shows or In Angular 2, you use property binding; there is no built-in hide
hides the associated HTML element based on an directive. For more information, see ng-show.
expression. For more information, see ng-show.

ng-href bind to the href property

<a ng-href="angularDocsUrl">Angular <a [href]="angularDocsUrl">Angular Docs</a>


Docs</a>

The ng-href directive allows Angular 1 to Angular 2, uses property binding; there is no built-in href directive.
preprocess the href property so that it can Place the element's href property in square brackets and set it to a
replace the binding expression with the quoted template expression.
appropriate URL before the browser fetches from
that URL. For more information on property binding, see Template Syntax.

In Angular 1, the ng-href is often used to In Angular 2, href is no longer used for routing. Routing uses
activate a route as part of navigation. routerLink , as shown in the third example.

<a ng-href="#movies">Movies</a> <a [routerLink]="['/movies']">Movies</a>

Routing is handled differently in Angular 2.


For more information on routing, see Routing & Navigation.

ng-if *ngIf

<table ng-if="movies.length"> <table *ngIf="movies.length">

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 5/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

In Angular 1, the ng-if directive removes or


recreates a portion of the DOM, based on an The *ngIf directive in Angular 2 works the same as the ng-if
expression. If the expression is false, the element directive in Angular 1. It removes or recreates a portion of the DOM
is removed from the DOM. based on an expression.

In this example, the table element is removed In this example, the table element is removed from the DOM
from the DOM unless the movies array has a unless the movies array has a length.
length greater than zero.
The (*) before ngIf is required in this example. For more
information, see Structural Directives.

ng-model ngModel

<input ng-model="vm.favoriteHero"/> <input [(ngModel)]="favoriteHero" />

In Angular 1, the ng-model directive binds a


form control to a property in the controller In Angular 2, two-way binding is denoted by [()] , descriptively
associated with the template. This provides two- referred to as a "banana in a box". This syntax is a shortcut for
way binding, whereby any change made to the de ning both property binding (from the component to the view)
value in the view is synchronized with the model, and event binding (from the view to the component), thereby
and any change to the model is synchronized providing two-way binding.
with the value in the view.
For more information on two-way binding with ngModel, see
Template Syntax.

ng-repeat *ngFor

<tr ng-repeat="movie in vm.movies"> <tr *ngFor="let movie of movies">

In Angular 1, the ng-repeat directive repeats


the associated DOM element for each item in the The *ngFor directive in Angular 2 is similar to the ng-repeat
speci ed collection. directive in Angular 1. It repeats the associated DOM element for
each item in the speci ed collection. More accurately, it turns the
In this example, the table row ( tr ) element de ned element ( tr in this example) and its contents into a
repeats for each movie object in the collection of template and uses that template to instantiate a view for each item
movies. in the list.

Notice the other syntax differences: The (*) before ngFor is


required; the let keyword identi es movie as an input variable;
the list preposition is of , not in .

For more information, see Structural Directives.

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 6/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

ng-show bind to the hidden property

<h3 ng-show="vm.favoriteHero"> <h3 [hidden]="!favoriteHero">


Your favorite hero is: Your favorite hero is: {{favoriteHero}}
{{vm.favoriteHero}} </h3>
</h3>

In Angular 1, the ng-show directive shows or Angular 2, uses property binding; there is no built-in show directive.
hides the associated DOM element, based on an For hiding and showing elements, bind to the HTML hidden
expression. property.

In this example, the div element is shown if the To conditionally display an element, place the element's hidden
favoriteHero variable is truthy. property in square brackets and set it to a quoted template
expression that evaluates to the opposite of show.

In this example, the div element is hidden if the favoriteHero


variable is not truthy.

For more information on property binding, see Template Syntax.

ng-src bind to the src property

<img ng-src="{{movie.imageurl}}"> <img [src]="movie.imageurl">

The ng-src directive allows Angular 1 to


preprocess the src property so that it can Angular 2, uses property binding; there is no built-in src directive.
replace the binding expression with the Place the src property in square brackets and set it to a quoted
appropriate URL before the browser fetches from template expression.
that URL.
For more information on property binding, see Template Syntax.

ng-style ngStyle

<div ng-style="{color: <div [ngStyle]="{color: colorPreference}">


colorPreference}"> <div [style.color]="colorPreference">

In Angular 1, the ng-style directive sets a CSS


style on an HTML element based on an In Angular 2, the ngStyle directive works similarly. It sets a CSS
expression. That expression is often a key-value style on an HTML element based on an expression.
control object with each key of the object de ned
as a CSS style name, and each value de ned as In the rst example, the color style is set to the current value of

an expression that evaluates to a value the colorPreference variable.


appropriate for the style.
https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 7/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

In the example, the color style is set to the Angular 2 also has style binding, which is good way to set a single
current value of the colorPreference variable. style. This is shown in the second example.

For more information on style binding, see Template Syntax.

For more information on the ngStyle directive, see Template Syntax.

ng-switch ngSwitch

<div ng-switch="vm.favoriteHero && <span [ngSwitch]="favoriteHero &&


checkMovieHero(favoriteHero)">
vm.checkMovieHero(vm.favoriteHero)"> <p *ngSwitchCase="true">
<div ng-switch-when="true"> Excellent choice!
Excellent choice! </p>
</div> <p *ngSwitchCase="false">
<div ng-switch-when="false"> No movie, sorry!
No movie, sorry! </p>
</div> <p *ngSwitchDefault>
<div ng-switch-default> Please enter your favorite hero.
Please enter your favorite </p>
hero. </span>
</div>
</div>
In Angular 2, the ngSwitch directive works similarly. It displays an
In Angular 1, the ng-switch directive swaps the
element whose *ngSwitchCase matches the current ngSwitch
contents of an element by selecting one of the
expression value.
templates based on the current value of an
expression. In this example, if favoriteHero is not set, the ngSwitch value
is null and *ngSwitchDefault displays, "Please enter ...". If
In this example, if favoriteHero is not set, the
favoriteHero is set, the app checks the movie hero by calling a
template displays "Please enter ...". If
component method. If that method returns true , the app selects
favoriteHero is set, it checks the movie hero
*ngSwitchCase="true" and displays: "Excellent choice!" If that
by calling a controller method. If that method
methods returns false , the app selects
returns true , the template displays "Excellent
*ngSwitchCase="false" and displays: "No movie, sorry!"
choice!". If that methods returns false , the
template displays "No movie, sorry!". The (*) before ngSwitchCase and ngSwitchDefault is required
in this example.

For more information on the ngSwitch directive, see Template


Syntax.

Back to top

Filters/pipes
https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 8/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

Angular 2 pipes provide formatting and transformation for data in our template, similar to Angular 1 lters. Many of the built-in
lters in Angular 1 have corresponding pipes in Angular 2. For more information on pipes, see Pipes.

Angular 1 Angular 2

currency currency

<td>{{movie.price | currency}}</td> <td>{{movie.price |


currency:'USD':true}}</td>
Formats a number as a currency.

The Angular 2 currency pipe is similar although


some of the parameters have changed.

date date

<td>{{movie.releaseDate | date}}</td> <td>{{movie.releaseDate | date}}</td>

Formats a date to a string based on the requested


format. The Angular 2 date pipe is similar.

lter none
For performance reasons, no comparable pipe exists in
<tr ng-repeat="movie in movieList |
Angular 2. Do all your ltering in the component. If you
filter: {title:listFilter}">
need the same ltering code in several templates,
Selects a subset of items from the de ned collection, consider building a custom pipe.
based on the lter criteria.

json json

<pre>{{movie | json}}</pre> <pre>{{movie | json}}</pre>

Converts a JavaScript object into a JSON string. This is


useful for debugging. The Angular 2 json pipe does the same thing.

limitTo slice

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 9/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

<tr ng-repeat="movie in movieList | <tr *ngFor="let movie of movies |


limitTo:2:0"> slice:0:2">

Selects up to the rst parameter (2) number of items


from the collection starting (optionally) at the The SlicePipe does the same thing but the order of
beginning index (0). the parameters is reversed, in keeping with the
JavaScript Slice method. The rst parameter is the
starting index; the second is the limit. As in Angular 1,
coding this operation within the component instead
could improve performance.

lowercase lowercase

<div>{{movie.title | lowercase}}</div> <td>{{movie.title | lowercase}}</td>

Converts the string to lowercase.


The Angular 2 lowercase pipe does the same thing.

number number

<td>{{movie.starRating | number}}</td> <td>{{movie.starRating | number}}</td>


<td>{{movie.starRating | number:'1.1-
Formats a number as text. 2'}}</td>
<td>{{movie.approvalRating | percent:
'1.0-2'}}</td>

The Angular 2 number pipe is similar. It provides more


functionality when de ning the decimal places, as
shown in the second example above.

Angular 2 also has a percent pipe, which formats a


number as a local percentage as shown in the third
example.

orderBy none
For performance reasons, no comparable pipe exists in
<tr ng-repeat="movie in movieList |
Angular 2. Instead, use component code to order or
orderBy : 'title'">
sort results. If you need the same ordering or sorting
Displays the collection in the order speci ed by the code in several templates, consider building a custom
expression. In this example, the movie title orders the pipe.

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 10/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

movieList.

Back to top

Modules/controllers/components
In both Angular 1 and Angular 2, Angular modules help you organize your application into cohesive blocks of functionality.

In Angular 1, you write the code that provides the model and the methods for the view in a controller. In Angular 2, you build a
component.

Because much Angular 1 code is in JavaScript, JavaScript code is shown in the Angular 1 column. The Angular 2 code is shown
using TypeScript.

Angular 1 Angular 2

IIFE none
You don't need to worry about this in Angular 2 because
(function () {
you use ES 2015 modules and modules handle the
...
}()); namespacing for you.

In Angular 1, you often de ned an immediately invoked For more information on modules, see Architecture
function expression (or IIFE) around your controller Overview.
code. This kept your controller code out of the global
namespace.

Angular modules Angular modules

angular.module("movieHunter", import { NgModule } from


["ngRoute"]); '@angular/core';
import { BrowserModule } from
In Angular 1, an Angular module keeps track of '@angular/platform-browser';
controllers, services, and other code. The second
argument de nes the list of other modules that this import { AppComponent } from

module depends upon. './app.component';

@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 11/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

Angular 2 modules, de ned with the NgModule


decorator, serve the same purpose:

imports : speci es the list of other modules that

this module depends upon


declaration : keeps track of your components,

pipes, and directives.

For more information on modules, see Angular


Modules.

Controller registration Component Decorator

angular @Component({
.module("movieHunter") moduleId: module.id,
.controller("MovieListCtrl", selector: 'movie-list',
["movieService", templateUrl: 'movie-
MovieListCtrl]); list.component.html',
styleUrls: [ 'movie-
Angular 1, has code in each controller that looks up an list.component.css' ],
appropriate Angular module and registers the controller })

with that module.

Angular 2, adds a decorator to the component class to


The rst argument is the controller name. The second
argument de nes the string names of all dependencies provide any required metadata. The Component
decorator declares that the class is a component and
injected into this controller, and a reference to the
controller function. provides metadata about that component such as its
selector (or tag) and its template.

This is how you associate a template with code, which


is de ned in the component class.

For more information, see the Components section of


the Architecture Overview page.

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 12/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

Controller function Component class

function MovieListCtrl(movieService) { export class MovieListComponent {


} }

In Angular 1, you write the code for the model and


methods in a controller function. In Angular 2, you create a component class.

NOTE: If you are using TypeScript with Angular 1, you


must use the export keyword to export the
component class.

For more information, see the Components section of


the Architecture Overview page.

Dependency injection Dependency injection

MovieListCtrl.$inject = ['MovieService']; constructor(movieService: MovieService)


function MovieListCtrl(movieService) { {
} }

In Angular 1, you pass in any dependencies as


controller function arguments. This example injects a In Angular 2, you pass in dependencies as arguments
MovieService . to the component class constructor. This example
injects a MovieService . The rst parameter's
To guard against mini cation problems, tell Angular TypeScript type tells Angular what to inject, even after
explicitly that it should inject an instance of the mini cation.
MovieService in the rst parameter.
For more information, see the Dependency Injection
section of the Architecture Overview.

Back to top

Style sheets
Style sheets give your application a nice look. In Angular 1, you specify the style sheets for your entire application. As the
application grows over time, the styles for the many parts of the application merge, which can cause unexpected results. In
Angular 2, you can still de ne style sheets for your entire application. But now you can also encapsulate a style sheet within a
speci c component.

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 13/14
11/20/2016 Angular 1 to 2 Quick Reference ­ ts ­ COOKBOOK

Angular 1 Angular 2

Link tag Link tag

<link href="styles.css" rel="stylesheet" <link rel="stylesheet"


/> href="styles.css">

Angular 1, uses a link tag in the head section of the


index.html le to de ne the styles for the In Angular 2, you can continue to use the link tag to
application. de ne the styles for your application in the
index.html le. But now you can also encapsulate
styles for your components.

StyleUrls
In Angular 2, you can use the styles or styleUrls
property of the @Component metadata to de ne a
style sheet for a particular component.

styleUrls: [ 'movie-list.component.css'
],

This allows you to set appropriate styles for individual


components that won’t leak into other parts of the
application.

Back to top

https://angular.io/docs/ts/latest/cookbook/a1­a2­quick­reference.html 14/14

You might also like