You are on page 1of 24

 Template basics - binding and local variables.

 Template directives - built-in directives ngIf and ngClass.

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

 Modules/controllers/components - modules in Angular 2 are slightly different


from modules in Angular 1, and controllers are componentsin 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:


{{vm.favoriteHero}} {{favoriteHero}}

In Angular 1, an expression in curly


In Angular 2, a template expression in
braces denotes one-way binding.
curly braces still denotes one-way binding.
This binds the value of the element This binds the value of the element to a
to a property in the controller property of the component. The context of
associated with this template. the binding is implied and is always the
associated component, so it needs no
When using the controller reference variable.
as syntax, the binding is prefixed
with the controller alias For more information, see
(vm or $ctrl) because you have to the Interpolation section of the Template
be specific about the source of the Syntax page.
binding.

Filters Pipes

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


uppercase}}</td>
In Angular 2 you use similar syntax with
To filter output in Angular 1
the pipe (|) character to filter output, but
templates, use the pipe character
now you call them pipes. Many (but not
(|) and one or more filters.
all) of the built-in filters from Angular 1 are

This example filters built-in pipes in Angular 2.

the title property to uppercase.


For more information, see the
heading Filters/pipes below.
Local variables Input variables

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


vm.movies"> <td>{{movie.title}}</td>
<td>{{movie.title}}</td> </tr>
</tr>
Angular 2 has true template input variables
Here, movie is a user-defined local
that are explicitly defined using
variable.
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
ng-app Bootstrapping
main.ts
<body ng-app="movieHunter">

The application startup process import { platformBrowserDynamic } from


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

Although you can bootstrap an


platformBrowserDynamic().bootstrapModule(
Angular 1 app in code, many
AppModule);
applications bootstrap
declaratively with the ng-
app.module.ts
app directive, giving it the name
of the application's module import { NgModule } from
(movieHunter). '@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: <div [ngClass]="{active: isActive}">


isActive}"> <div [ngClass]="{active: isActive,
<div ng-class="{active: shazam: isImportant}">
isActive, <div [class.active]="isActive">
shazam:
isImportant}">
In Angular 2, the ngClass directive works

In Angular 1, the ng- similarly. It includes/excludes CSS classes

class directive based on an expression.

includes/excludes CSS classes


In the first example, the active class is
based on an expression. That
applied to the element if isActive is true.
expression is often a key-value
control object with each key of
You can specify multiple classes, as shown in
the object defined as a CSS
the second example.
class name, and each value
defined as a template
Angular 2 also has class binding, which is a
expression that evaluates to a
good way to add or remove a single class, as
Boolean value.
shown in the third example.

In the first example,


For more information see the Attribute, Class,
the active class is applied to
and Style Bindingssection of the Template
the element if isActive is true. Syntax page.

You can specify multiple


classes, as shown in the
second example.

ng-click bind to the click event

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


click="vm.toggleImage()"> <button (click)="toggleImage($event)">
<button ng-
click="vm.toggleImage($event
Angular 1 event-based directives do not exist
)"> in Angular 2. Rather, define one-way binding
In Angular 1, the ng- from the template view to the component
click directive allows you to using event binding.
specify custom behavior when
an element is clicked. For event binding, define the name of the
target event within parenthesis and specify a
In the first example, when the template statement, in quotes, to the right of
user clicks the button, the equals. Angular 2 then sets up an event
the toggleImage() method in handler for the target event. When the event is
the controller referenced by raised, the handler executes the template
the vm controller as alias is statement.
executed.
In the first example, when a user clicks the
The second example button, the toggleImage() method in the
demonstrates passing in associated component is executed.
the $event object, which The second example demonstrates passing in
provides details about the event the $event object, which provides details
to the controller. 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- @Component({


controller="MovieListCtrl as moduleId: module.id,
vm"> selector: 'movie-list',

In Angular 1, the ng- templateUrl: 'movie-


list.component.html',
controller directive attaches
styleUrls: [ 'movie-list.component.css'
a controller to the view. Using
],
the ng-controller (or defining
})
the controller as part of the
routing) ties the view to the In Angular 2, the template no longer specifies

controller code associated with its associated controller. Rather, the

that view. component specifies 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- In Angular 2, you use property binding; there


hide directive shows or hides is no built-in hidedirective. For more
the associated HTML element information, see ng-show.
based on an expression. For
more information, see ng-show.

ng-href bind to the href property

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


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

In Angular 2, href is no longer used for


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

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


href="#movies">Movies</a>
For more information on routing, see Routing
Routing is handled differently in
& Navigation.
Angular 2.

ng-if *ngIf

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


if="movies.length">
The *ngIf directive in Angular 2 works the
In Angular 1, the ng-
same as the ng-ifdirective in Angular 1. It
if directive removes or
removes or recreates a portion of the DOM
recreates a portion of the DOM,
based on an expression.
based on an expression. If the
expression is false, the element
In this example, the table element is
is removed from the DOM.
removed from the DOM unless
the movies array has a length.
In this example,
the table element is removed
The (*) before ngIf is required in this
from the DOM unless
example. For more information, see Structural
the movies array has a length
Directives.
greater than zero.
ng-model ngModel

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


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

ng-repeat *ngFor

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


vm.movies">
The *ngFor directive in Angular 2 is similar to
In Angular 1, the ng-
the ng-repeatdirective in Angular 1. It
repeat directive repeats the
repeats the associated DOM element for each
associated DOM element for
item in the specified collection. More
each item in the specified
accurately, it turns the defined element (tr in
collection. this example) and its contents into a template
and uses that template to instantiate a view for
In this example, the table row each item in the list.
(tr) element repeats for each
movie object in the collection of Notice the other syntax differences: The (*)
movies. before ngFor is required; the let keyword
identifies movie as an input variable; the list
preposition is of, not in.

For more information, see Structural


Directives.

ng-show bind to the hidden property

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


show="vm.favoriteHero"> Your favorite hero is: {{favoriteHero}}
Your favorite hero is: </h3>
{{vm.favoriteHero}}
</h3>
Angular 2, uses property binding; there is no

In Angular 1, the ng- built-in show directive. For hiding and showing

show directive shows or hides elements, bind to the HTML hiddenproperty.

the associated DOM element,


To conditionally display an element, place the
based on an expression.
element's hiddenproperty in square brackets

In this example, and set it to a quoted template expression that

the div element is shown if evaluates to the opposite of show.

the favoriteHero variable is


In this example, the div element is hidden if
truthy. the favoriteHerovariable is not truthy.

For more information on property binding,


see Template Syntax.

ng-src bind to the src property

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


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

ng-style ngStyle

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


colorPreference}"> colorPreference}">

In Angular 1, the ng- <div [style.color]="colorPreference">

style directive sets a CSS


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

the object defined as a CSS the current value of

style name, and each value the colorPreference variable.

defined as an expression that


Angular 2 also has style binding, which is
evaluates to a value appropriate
good way to set a single style. This is shown
for the style.
in the second example.

In the example, the color style


For more information on style binding,
is set to the current value of
see Template Syntax.
the colorPreference variable.

For more information on the ngStyle directive,


see Template Syntax.

ng-switch ngSwitch

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


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

Back to top
Filters/pipes
Angular 2 pipes provide formatting and transformation for data in our template, similar
to Angular 1 filters. Many of the built-in filters 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 | <td>{{movie.price |
currency}}</td> currency:'USD':true}}</td>

Formats a number as a
The Angular 2 currency pipe is similar
currency.
although some of the parameters have
changed.

date date

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


date}}</td>
The Angular 2 date pipe is similar.
Formats a date to a string
based on the requested format.
filter none

For performance reasons, no comparable pipe


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

json json

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

Converts a JavaScript object


The Angular 2 json pipe does the same thing.
into a JSON string. This is
useful for debugging.

limitTo slice

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


movieList | limitTo:2:0"> slice:0:2">

Selects up to the first parameter


The SlicePipe does the same thing but
(2) number of items from the
the order of the parameters is reversed, in
collection starting (optionally) at keeping with the JavaScript Slicemethod.
the beginning index (0). The first 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 | <td>{{movie.title | lowercase}}</td>


lowercase}}</div>
The Angular 2 lowercase pipe does the same
Converts the string to
thing.
lowercase.

number number

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


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 defining 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


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


(function () {
Angular 2 because you use ES 2015
...
modules and modules handle the
}());
namespacing for you.
In Angular 1, you often defined an
immediately invoked function
For more information on modules,
expression (or IIFE) around your
see Architecture Overview.
controller code. This kept your
controller code out of the global
namespace.

Angular modules Angular modules

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


["ngRoute"]); '@angular/core';

In Angular 1, an Angular module keeps import { BrowserModule } from


'@angular/platform-browser';
track of controllers, services, and other
code. The second argument defines the
import { AppComponent } from
list of other modules that this module './app.component';

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

Angular 2 modules, defined with


the NgModule decorator, serve the
same purpose:

 imports: specifies 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',
Angular 1, has code in each controller styleUrls: [ 'movie-
list.component.css' ],
that looks up an appropriate Angular
})
module and registers the controller with
that module. Angular 2, adds a decorator to the
component class to provide any
The first argument is the controller required metadata. The Component
name. The second argument defines decorator declares that the class is a
the string names of all dependencies component and provides metadata
injected into this controller, and a about that component such as its
reference to the controller function. selector (or tag) and its template.

This is how you associate a template


with code, which is defined in the
component class.

For more information, see


the Components section of the
Architecture Overview page.

Controller function Component class

function export class MovieListComponent {


MovieListCtrl(movieService) { }
}
In Angular 2, you create a component
In Angular 1, you write the code for the
class.
model and methods in a controller

NOTE: If you are using TypeScript


function. 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 = constructor(movieService:
['MovieService']; MovieService) {
function }
MovieListCtrl(movieService) {
}
In Angular 2, you pass in

In Angular 1, you pass in any dependencies as arguments to the

dependencies as controller function component class constructor. This

arguments. This example injects example injects a MovieService. The

a MovieService. first parameter's TypeScript type tells


Angular what to inject, even after
To guard against minification problems, minification.
tell Angular explicitly that it should inject
an instance of the MovieService in the For more information, see

first parameter. 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 define style sheets for your entire application. But now you can also
encapsulate a style sheet within a specific component.

Angular 1 Angular 2

Link tag Link tag

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


rel="stylesheet" />
In Angular 2, you can continue to use the link tag
Angular 1, uses a link tag in
to define the styles for your application in
the head section of
the index.html file. But now you can also
the index.html file to define
encapsulate styles for your components.
the styles for the application.

StyleUrls

In Angular 2, you can use


the styles or styleUrlsproperty of
the @Component metadata to define 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.