# Angular 2.0 tutorial: templates with working examples

Paul Shan Thu Nov 05 2015
Angular 2.0 is still beta (I’m using beta.1 here). If you find any difficulties to implement those what's written in the article (though I will try to keep the article updated always), please post a comment about that. Refer to the github repo for working examples.

In our Angular2 tutorial series we completed various ng2 tutorials. If you have not scaffolded your angular 2 app yet, you can have a look at how to scaffold and make hello world using angular 2.

This article assumes you have basing understanding of template engines and familiar with Angular 1.X or any other MVC framework where templates are used and focuses on how exactly you should different helpers, directives etc in Angular 2 templates. The article also assumes that you know how to write a basic ng 2 app.

An working copy of the example given in the article, can be found on the github repo ng-examples. You can simply clone and download and in your terminal or command prompt just run the command live-server.

## Data printing

We are well aware of double curly braces and Angular 2.0 also went with the similar approach for data printing.

### {{printMe}}

import {Component, View} from 'angular2/core';
@Component({
selector: 'data-print',

})
@View({
template:
Data Print

My name is: {{title}} {{fName}} {{lName}}

})
export class DataPrint {
title = 'Mr.';
fName = 'Paul';
lName = 'Shan';
gravatar = 'http://www.gravatar.com/avatar/48692c25db0cdbbe426d6c3dc947ecb2';
}


### {{me+you}}

import {Component, View} from 'angular2/core';
@Component({
selector: 'data-operations',

})
@View({
template:
Data Operations
1 + 1 = {{1+1}}
{{value1}} + {{value2}} = {{value1 + value2}}

})
export class DataOperations {
value1 = 10;
value2 = 10;
}


## Events and refs

As now we know the very basic step of templating; i.e. printing values, it’s time to deal with events and another thing called refs, which is nothing but something like a variable to point to an element.

### (click)=”onMyClick()”

import {Component, View} from 'angular2/core';
@Component({
selector: 'event-change',

})
@View({
template:
Events


})
export class EventsAndChange {
shout:function () {
}
}


### #myRef

import {Component, View} from 'angular2/core';
@Component({
selector: 'event-ref',

})
@View({
template:
Events & Ref


})
export class EventsAndRef {
displayInputValue:function (element) {
//element id the dom element.
var textInInput = element.value;
if (!textInInput)
else
}
}


You can give a name to any of the element with a hash prefix; and once you named it, you can use it anywhere inside that template.

Remember you can not use snake case names for your ref.

## Value, attribute, class & style

You need to keep in mind that the expression written inside double quotes are executed in the templates if it’s written at the right hand side against any of the expressions below in the left hand side.

### input [value]=”myValue”

Alternative : bind-value=”myValue”

import {Component, View} from 'angular2/core';
@Component({
selector: 'input-value',

})
@View({
template:
Input Value

Input value is : {{myValue}}

})
export class InputValue {
myValue = 'Paul Shan';
chasngeMyValue:function (element) {
this.myValue = element.value;
};
resetMyValue:function () {
this.myValue = 'Paul Shan';
}
}


value={{myValue}} will also work, but it’s not what you are thinking (check the differences pointed out below). But if you use value=”myValue” this will not execute the “myValue” expression.

### [attr.title]=”titleSentence”

import {Component, View} from 'angular2/core';
@Component({
selector: 'attr-class',

})
@View({
template:
Attributes
Hover me - normal title
Hover me - [attr.title]

})
export class AttributeClass {
titleSentence = 'I am an executed title';
}


title={{titleSentence}} will also work, but not exactly how you are thinking (check the differences point below). But title=”titleSentence” won’t execute the expression titleSentence.

### [class.myClassName]=”isConditionTrue”

import {Component, View} from 'angular2/core';
@Component({
selector: 'attr-class',

})
@View({
template:

.classExampleRed{
color:red;
}

Classes


})
export class AttributeClass {
isRed = false;
isRedClassOn = function () {
return this.isRed;
}
toggleColor = function () {
this.isRed = !this.isRed;
}

}


Here the expression in the rightHand side must return boolean. For a truthy value it will keep that certain class, whereas a falsy value will remove the class.

### [style.myProperty.px]=”myExpression”

import {Component, View} from 'angular2/core';
@Component({
selector: 'attr-class',

})
@View({
template:
Style


})
export class AttributeClass {
myFontSize = 11;
toggleSize = function () {
if (this.myFontSize == 11)
this.myFontSize = 20;
else
this.myFontSize = 11;
}
}


This is also pretty similar to the other three above.

### Differences

Well, even though value={{myValue}} is working fine for you, but this is actually not working as you are thinking. If you write anything without the [attr.X], this is considered to be the a property and NOT AN ATTRIBUTE. For input element value is a default property; you just change it to value2={{myValue}} or [value2]=”myValue” and your application will break. A property belongs to the element whereas an attribute belongs to the DOM element.

## Built in directives

There are some built in directives to help you to work with very common helpers like, for, if etc. Below are the examples.

### *ngFor

import {Component, View} from 'angular2/core';
import {NgFor} from 'angular2/common';
@Component({
selector: 'if-for',

})
@View({
directives:[NgFor]
template:
NgFor Example

{{name}}


})
export class ForAndIf {
names = ["Paul", "David", "Jack"];
}


You must include the directive NgFor to use *ngFor in your template. Can you see the little asterisk (*) symbol just before ngFor? This is a syntactic thing to declare a template. Using this you are saying that the element in which you used, it itself is a template

### *ngIf

import {Component, View} from 'angular2/core';
import {NgIf} from 'angular2/common';

@Component({
selector: 'if-for',

})
@View({
directives:[NgIf]
template:
NgIf Example
Yes I am true

})
export class ForAndIf {
amITrue=true;
amIFalse=false;
}


The directive NgIf must be included in the component to use ngIf in your template. Here also we are using the asterisk (*) symbol. The reason is just same as ngFor.

### [ngSwitch]

import {Component, View} from 'angular2/core';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/common'

@Component({
selector: 'eg-switch',

})
@View({
directives: [NgSwitch, NgSwitchWhen, NgSwitchDefault]
template:
NgSwitch Example

Click to Change The number ::

One
Two
Three
Four
Five
Zero


})
export class SwitchTemplates {
myVal = 0;
increase: function () {
if (this.myVal === 5)
this.myVal = 0;
else
this.myVal++;
}
}


Along with the directive NgSwitch you also need to include two other directives NgSwitchWhen and NgSwitchDefault to implement the [ngSwitch] properly.

Here no asterisk (*) sign is used. Rather we explicitly said that this is the template element. Reason is, in case of switch statement, templates can be different for each and every when. Thus it was not possible for Angular 2 to make a common template tag. Thus, in case of switch, explicit declaration of template is required.

## Some interesting new comers in Ng 2

There are some really interesting features provided by Angular 2.0. Below are the examples.

### pipe

I personally consider pipe as a very necessary feature for UI. Because your api should always return the minimal data without considering how it should be displayed on the page. Pipe can modify the display of a certain variable easily. There are some built in types also like date etc.

import {Component, View} from 'angular2/core';
@Component({
selector: 'eg-pipe',

})
@View({
template:
Pipe Example
1. Today is {{today}}
2. Today is {{today | date}}
3. Today is {{today | date:"dd/MM/yyyy"}}

})
export class PipeExample {
today = new Date();

}


Apis are also available for custom pipes.

### Elvis operator

JavaScript executes a the variable path at runtime and if you write a variable like me.myName.firstName and if myName is undefined or falsy, the code will break there. We write ugly checks to avoid these code breaking. But from now on in Angular 2 apps you can use Elvis operator.

import {Component, View} from 'angular2/core';
@Component({
selector: 'eg-elvis',

})
@View({
template:
Elvis operator Example
This is working fine {{obj.temp}}
This line will break the application {{obj.temp.me.she.he}}. Please uncomment and check
This line will be printed but nothing on right side {{obj?.temp?.me?.she?.he}}

})
export class ElvisExample {
obj = {
temp:"I am temp"
}

}


The elvis operator skips the very right property if the left side is undefined or falsy.

angular2 tutorialangular 2angularjs

Written By

## Paul Shan

• E

• R

• C

• S

### SEO

Search engine optimization

• E

• C

### CMS

wordpress, drupal, jumla, magento and more

Show All

### Tags

vue-js
Web development
vue css
social share buttons
real-life-example
react datetime picker
progra
Online
MathJax
jsfiddle
jquery chart library
instant search using vue
handlebars
event loop
Design
console.log
best practices
imorph

Show All