0% found this document useful (1 vote)
5K views

Angular 2 Building Blocks Handson

Angular 2 is a JavaScript framework for building web and mobile applications. It uses TypeScript for safe coding and has enhancements over Angular 1.x that make it simpler to use. Angular 2 focuses on building JavaScript classes, provides flexibility in language choices like TypeScript, and has improved performance through server-side rendering and a hierarchical dependency injection system. Setting up an Angular 2 environment requires Node.js and installing Angular CLI, TypeScript, and other dependencies. The core architecture of Angular 2 consists of eight blocks including modules, components, templates and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
5K views

Angular 2 Building Blocks Handson

Angular 2 is a JavaScript framework for building web and mobile applications. It uses TypeScript for safe coding and has enhancements over Angular 1.x that make it simpler to use. Angular 2 focuses on building JavaScript classes, provides flexibility in language choices like TypeScript, and has improved performance through server-side rendering and a hierarchical dependency injection system. Setting up an Angular 2 environment requires Node.js and installing Angular CLI, TypeScript, and other dependencies. The core architecture of Angular 2 consists of eight blocks including modules, components, templates and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

What is Angular 2?

It is a JavaScript framework for creating web and mobile applications.


It supportsTypeScript, a super script of Javascript that helps in safe coding.
It has several enhancements on top of Angular 1.x, which makes it simple to use
and get the desired output. But knowledge in Angular 1.x is not necessary to
learn Angular 2, since the whole framework is re-written.

Why Angular 2?
Easy: Unlike previous versions, Angular 2 focuses only on building JavaScript
classes; hence it is easier to learn.
Freedom: It provides more choices of languages for consumption i.e. ES5, ES6,
Typescript, and Dart. TypeScript is recommended here.
Flexible: It is a Cross-platform framework.
Faster: Because of server side rendering.
Simpler: Component based approach with no controllers and $scope.
Performance: Uses Hierarchical Dependency Injection system, which is a
performance booster.

Angular 2 Environment Setup


To setup an Angular 2 environment, node.js is mandatory. Once node.js and npm
are available, you can run the following to complete the setup in cmd.

m
Install Angular CLI(command line interface) Command: npm i -g @angular/cli (-g

er as
installs angular globally for all users)

co
Install TypeScript Command: npm install -g typescript

eH w
Architecture

o.
You can see that the architecture of Angular 2 consists of eight basic blocks.
rs e
In order to learn Angular 2, a good understanding of architecture is necessary.
ou urc
------------

Angular 2 uses ______ Dependency Injection. Hierarchical


o
aC s

The following are true about Angular 2, except ________. Angular 2 extensively
v i y re

uses $scope object to implement MV* pattern

Which scripting language can be used to write Angular 2 apps? TypeScript or


JavaScript
ed d

Which of the following is one of the blocks of Angular 2 architecture? None


ar stu

Angular 2 is written on top of Angular 1.5.x. False

------------
sh is

What is Module?
A Module is a way of organizing related Components, Services, Directives, and
Th

Pipes with a specific functionality.

It is a block of code meant to do certain tasks.

There can be several Modules within an app, but it should consist of at least
one root module. Root Module, by convention, must be named: AppModule.

It can be exported and imported in other modules.

@NgModule is used to declare a Class as Module.

Module as library - Angular Module can act as a library of modules.


@angular/core is a most common library being used in building angular
application. It has most of the modules that are required for your app.

Module - Example

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
This is a sample code for module.

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


import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
// AppModule Class is now defined as Module : @NgModule

Trick to identify Root Module is that it imports "BrowserModule". Other modules


of that same application imports "CommonModule".
imports:[...] - define array of modules required to build application here.
declarations:[...] - define components, directives and pipes for this module
here.
bootstrap:[...] - define root component of this module here.

-----------

Root module class by convention is named as _______. AppModule

m
er as
The @Component decorator defines how an application should be compiled and

co
launched. False

eH w
What are the types of Angular View Classes that can be associated to a Module?

o.
Components, Directives and Pipes rs e
ou urc
The decorator that is used to indicate a module is _______. @NgModule

An app can have one or no modules present. False


o

What is it called when you "compile the application as part of the build
aC s

process"? Ahead-of-Time (AOT) Compilation


v i y re

-----------

What is Component?
A component is the basic block of angular 2 app.
ed d

It handles the view part of the app and has the core logic of the page.
ar stu

It can render the view by itself based on the dependency Injection.


There can be only one component per DOM element (i.e. only one selector
element).
Element's behavior can be manipulated by the properties associated with
corresponding component.
sh is

It can be identified using the decorator @Component.


Components can be created, updated or destroyed based on the user actions on the
Th

page.

Components - Example
This example will render Hello, World! in the browser. Angular will search for
<my-app> element in HTML file and replace it with the template content.

File: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<p>Hello, World!</p>',
})
export class AppComponent{}

File: index.html

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
............
<body>
<my-app> Loading... </my-app>
</body>
............

----------

Select the correct Component lifecycle sequence (Note: Not all lifecycle methods
are present).
ngOnChanges() -> ngOnInit() -> ngDoCheck() -> ngAfterContentChecked() ->
ngAfterViewInit() -> ngOnDestroy()

How many lifecycle methods does Angular offer apart from a Component's
constructor()? 8

There can be only one component per DOM element. True

______ element property is used to tell angular to insert the instance of


component in the HTML file. Selectors

Components can be used with ____________. Both

m
er as
______ are mandatory parameter in components. Templates

co
eH w
A _______ acts as a mediator between application/business logic and the
application presentation layer. Component

o.
-------------
rs e
ou urc
What is Template?
Template is a simple HTML code that creates view for a component, which you can
dynamically manipulate.
o
aC s

There are two ways to define templates:


v i y re

template
templateUrl

How to use Template?


When template is used, it defines code in the same file
ed d
ar stu

import {Component} from 'angular2/core';


@Component({
selector: 'greet',
template: `
//this defines template for 'greet' component
sh is

<h1>Hello There!!!</h1>
Th

<h2>Have a nice day.</h2>


` // back tick symbol (~ key on your keyboard)
//back tick is explained in detail in TypeScript
})
export class GreetApp {}

When templateUrl is used, the code is defined in different files and URL of the
corresponding files are referred.

import {Component} from 'angular2/core';


@Component({
selector: 'greet',
templateUrl: 'app.component.html'
//this defines "URL to the external file"
that defines template for 'greet' component
})
export class GreetApp {}

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
-----------

Give a Try - My First App

In app.component.ts :

selector: 'app-root',
template: '<h1>My first angular app</h1>',

-----------

What does the following code demonstrate? Use of Template Reference Variables
<input #empId placeholder="Enter your TCS employee id" required>

What happens when the following code is encountered by Angular? A template parse
error is thrown since colspan is a native HTML attribute
<tr>
<td id="tableData4" colspan={{2 * 2}}>
</td>
</tr

m
Templates handle the view part of the application. True

er as
co
Consider the following code. <p class="bold text-center"> {{data?.userName}}

eH w
</p>
<p class="bold text-center"> {{data.userName}} </p>

o.
The data object is fetched from a service and turns out to be null. In such a
rs e
case, how can you ensure that the app does not crash or log any errors?
ou urc
Which of the following is the correct usage of template syntax? <li
(click)="selectHero(hero)" *ngFor="let hero of heroes"></li>
o
aC s

Multiline template should be included within _________. ....


v i y re

-------------

What is Metadata?
In Angular 2, Metadata is vital in getting the code processed and shown on the
ed d

screen. Metadata means data of data, which gives more info about data.
ar stu

ex: var age : number = 20;


// 20 is data
// "number" is metadata, as it tells information of "data", its type, its size
etc.
sh is

Metadata - Example
Th

Let us consider a simple example code as shown below. Suppose you want to have a
component, Angular will consider it as a simple "class" until you explicitly use
"Decorator" and attach metadata to TypeScript.

Here, @Component is used to define a class as component.


Likewise, @pipe is used to tell Angular to define a class as pipe.

import {Component} from 'angular2/core';


@Component({ //METADATA
selector: 'greet',
template: `
<h1>Hello There!!!</h1>
<h2>Have a nice day.</h2> `
})
export class GreetApp {}

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
Simply put, everything in Angular 2 is a simple class, until you declare
metadata (@Component or @Pipe or @Decorator or @Injectable) to it.

---------

Which of the following helps you define Metadata for a class? Using Decorator

Everything in Angular 2 is a simple class, until you declare metadata. True

Which of the following are valid metadata properties? All

The following are all Angular metadata Decorators, except ________. @Bindable

The following are all metadata, except ________ @template

-----------

What is Data Binding?


It is the process of automatic synchronization of view and business logic. It
helps in connecting the Template (view - what user sees) with Component (back
end data/source).

m
There are four ways you can bind a data to the DOM depending on the direction

er as
the data flows.

co
eH w
Data flows into the view by Interpolation and Property Binding.
Data flows outside the view into the class by Event Binding.

o.
Data flows both ways by Two-Way Data Binding.
rs e
ou urc
Interpolation
Interpolation acts as local variable, which allows us to bind data from
"Component Class" onto your "Template".
o

It is defined using {{ }} double curly braces.


aC s

If we consider an example, 20 + 20 results in {{20 + 20}}, the actual


v i y re

mathematical calculation is done and output is displayed as 20 + 20 results in


40.
It can also access values from component class. Ex - {{myName}}
It can further assign attributes to the tags. Ex - <img src = {{myImageURL}}>
ed d

------------
ar stu

Give a Try- Interpolation

In app.component.ts :
sh is

template: '<h1>{{message}}</h1>',
Th

message = '<h1>hey there</h1>';

-----------

Property Binding vs Interpolation


Both are same, as they make the data flow from "Component" to "Template". The
only difference is the way they are defined or used.

Interpolation Demo

import { component } from `@angular2/core`;


@Component ({
selector: 'myApp',
template: `
<h1> {{title}} </h1> //Interpolation Binding `
})

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
export class AppComponent {
title: "Hello Fresco !"
}

Property Binding Demo

import { component } from `@angular2/core`;


@Component ({
selector: 'myApp',
template: `
<h1 [innerHtml] = "title"> </h1> //Property Binding
`
})
export class AppComponent {
title: "Hello Fresco !"
}

------------------

Give a Try - Property Binding

In app.component.ts :

m
er as
message = 'hey there';

co
eH w
In app.component.html :

o.
<div> rs e
<span [innerHTML]="message"></span>
ou urc
</div>

-----------------
o

Event Binding
aC s

User interaction on view generates "Events" that make data flow from "Template"
v i y re

to "Component". It is defined using () paranthesis.

-------------------
ed d

Give a Try - Event Binding


ar stu

In app.component.ts :

name = "John Doe";


show = false;
sh is

welcomeMe(username: string)
Th

{
this.name = username;
this.show = true;
}

In app.component.html :

Welcome {{name}}

-------------

Two-Way Data Binding


Property Binding and Event Binding are One Way Data Binding. In other words,
data will flow either from Component to View or the other way, but not both.

Two-way data binding is a combination of both Property Binding and Event Binding

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
allowing us to update data in both directions. It is defined using [( )]
popularly known as banana brackets.

-----------------

Try it out - Two Way Data Binding

In app.component.ts :

name = {
first: "John",
last: "Smith"
}

In app.component.html :

Welcome {{name.first}} {{name.last}}

-------------------

m
Which of the following correctly represents one-way data binding, from source to

er as
view? <fresco-quiz [quizId]="frescoId"></fresco-quiz>

co
eH w
Which of the following correctly represents one-way data binding, from view to
source? <button (click) ="buttonClicked()">Click Me!</button>

o.
rs e
Which of the following correctly represents two-way data binding? <input
ou urc
type="password" [(ngModel)]="userPwd" required>

In order to bind data from view to component class, you can use _____. Event
binding
o
aC s

Two way binding is defined using ___________. [()]


v i y re

Two way binding is done using ________. [(ngModel)]

Property binding is defined using _________. []


ed d

Interpolation uses ________. {{}}


ar stu

Which Angular module helps you achieve two-way data binding? FormsModule

Data binding helps in synchronizing _______. Template and components


sh is

---------------
Th

What are Directives?


Directive is a class with @Directive decorator. They make DOM elements dynamic,
by changing their behavior.

Directive is of three types: Structural, Attribute and Component.

Structural Directive
They manipulate the DOM elements. i.e. Delete or update the elements. This
changes the structure of webpage.

Some of the built-in structural directives, Angular 2 offers are NgIf, NgFor and
NgSwitch.
Example: <div *ngIf="employee">{{employee.name}}</div>

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
Attribute Directive
These directives add styling by manipulating the Attributes of DOM element. They
do not change the structure of webpage.

NgStyle and NgClass are some of the built-in attribute directives, Angular 2
provides.

Technically Components is a subset of directives except the fact that they have
a mandatory template parameter.

------------

Which of the following is an Attribute Directive? NgModel

NgFor and NgIf are examples of _________. Structural

Which directive lets you modify the behavior of another Directive? Attribute

Which directive lets you change the rendered view by adding and removing
elements from the Document Object Model? Structural

m
The following are all Directives, except __________. Module

er as
co
ngOnInit will be initialized every time the template re-renders. False

eH w
What happens to the <div> element once the application is launched? <div

o.
*ngIf="servePie"> Pie Chart – Sales Projection ..... </div>
rs e
If 'servePie' evaluates to false, the element is destroyed from the DOM
ou urc
----------

What is Service?
o

Services are functions that are designed to complete a specific task. If you
aC s

want to bring external data from server into your app or perform some repetitive
v i y re

task, then services come handy.

How to use Services?

Create a file <serviceName>.services.ts.


ed d

Import injectable from @angular/core.


ar stu

Create a class with the required function and use the decorator @injectable() to
specify that it is a service.
Then import the service in root component, which is discussed in Dependency
Injection.
sh is

Example: This simple service will perform add operation whenever it is used.
Th

import {Injectable} from 'angular2/core';

@Injectable()
export class MyService {
addFunction(a,b){ return a+b; }
}

What is Dependency Injection?


Dependency Injection is a way to "Inject" the parameters or services
(dependencies), on which the new Instance is "Dependent" for its creation. How
the dependencies are created is not a point of concern for the instance
consuming the dependency.

Angular finds which services are required to the component, by looking at the
"type" of component's constructor parameters.
Angular then checks for the service in Injector, which makes a container of all

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
services that have already been created.
You will learn more about Services and Dependency Injection in detail in a
different course.

------------

Which of the following is an advantage of lazy loading? All

The following are true about Services, except ________. Services are designed to
do a lot of things at a time

How will you make sure that a single instance of any Service is available
throughout the app?
Register the service using 'providers' and add it to the Root Module

Services are included in components using ______. Provider

Services are identified using the decorator ______. @Injectable

There can be only one service in a component. False

-----------

m
er as
Hands on - Build Your Activity Tracker

co
eH w
In app.component.ts :

o.
public done: boolean; rs e
public todos : any;
ou urc
public newToDo : string;
public newToDoObj : any;
public error : boolean;
o

constructor(){
aC s

this.todos = [];
v i y re

this.newToDo = '';
this.error = false;

}
ed d

addMore(){
ar stu

this.todos.push({done : true, item : this.newToDo});


}

clearAll(){
this.todos = [];
sh is

}
Th

----------------------

Angular finds which services are required for the component by looking at the
"type" of the component's ________ parameters. constructor

Templates can also be added using URLs of the file containing code. True

This study source was downloaded by 100000825999107 from CourseHero.com on 06-13-2021 23:19:01 GMT -05:00

https://www.coursehero.com/file/68304897/Angular-2-Building-Blocks-Handsontxt/
Powered by TCPDF (www.tcpdf.org)

You might also like