You are on page 1of 41

SYLLABUS OF ANGULAR 4

CHAPTER 1

INTRODUCTION TO ANGULAR 4

1.1 What is Angular 4?

Angular is a platform that makes it easy to build applications with the web.
Angular combines declarative templates, dependency injection, end to end tooling,
and integrated best practices to solve development challenges. Angular empowers
developers to build applications that live on the web, mobile, or the desktop.

Angular is a framework that is used for creating client applications in CSS,


HTML and either JavaScript or TypeScript that can be compiled or transpired to
JavaScript. In total, there are three major versions of Angular. The first release was
of Angular1 in 2010, which is also termed as AngularJS. Angular1 was followed
by Angular2, which was released in 2016 with many different features.

The Angular structure is based on the services architecture. It is distributed


through a bunch of npm packages that are under the name of Angular. The
AngularJS was based on the model view controller. The major versions that are
currently available are 2, 4 and 5. Version 3 was skipped because the router
package was at version 3 and all the other packages were at version 2. The release
of Angular 4 in March 2017 proves to be a major breakthrough as it is the latest
Angular release and it provides many enhancements in comparison to Angular2.
Angular 4 comes with inbuilt Animation Package, form Validator attributes,
template, titlecase pipe and more. Angular 4 has many similarities and a backward
compatibility with Angular 2. Projects developed in Angular 2 can work
seamlessly in Angular 4. More than 98% of the code is the same for these two
versions with the same founding logic.
1.2 Central Features of the Angular Framework

With Angular Universal, it’s possible to render Angular applications outside


of the browser, for instance directly on the web server. With that, JavaScript is no
longer necessary for initially rendering the page content, so websites can be
optimized better for search engines. Another use case is the utilization of
WebWorker Threads to render content outside the GUI Thread. This rendered
content can simply be added to the DOM Tree for display later.

1.3 Why Angular?

ngIf

Angular2 supported only the if condition. However, Angular 4 supports the


if else condition as well. Let us see how it works using the ng-template.

<span *ngIf="isavailable; else condition1">Condition is valid.</span>

<ng-template #condition1>Condition is invalid</ng-template>

as keyword in for loop

With the help of as keyword you can store the value as shown below −

<div *ngFor="let i of months | slice:0:5 as total">

Months: {{i}} Total: {{total.length}}

</div>

The variable total stores the output of the slice using the as keyword.

Animation Package

Animation in Angular 4 is available as a separate package and needs to be


imported from @angular/animations. In Angular2, it was available with
@angular/core. It is still kept the same for its backward compatibility aspect.
Template

Angular 4 uses <ng-template> as the tag instead of <template>; the latter


was used in Angular2. The reason Angular 4 changed <template> to <ng-
template> is because of the name conflict of the <template> tag with the html
<template> standard tag. It will deprecate completely going ahead. This is one of
the major changes in Angular 4.

TypeScript 2.2

Angular 4 is updated to a recent version of TypeScript, which is 2.2. This


helps improve the speed and gives better type checking in the project.

Pipe Title Case

Angular 4 has added a new pipe title case, which changes the first letter of
each word into uppercase.

<div>

<h2>{{ 'Angular 4 titlecase' | titlecase }}</h2>

</div>

The above line of code generates the following output – Angular 4 Titlecase.

Http Search Parameters

Search parameters to the http get api is simplified. We do not need to call
URLSearchParams for the same as was being done in Angular2.

Smaller and Faster Apps

Angular 4 applications are smaller and faster when compared to Angular2. It


uses the TypeScript version 2.2, the latest version which makes the final
compilation small in size.
1.4 Scope and Goal of Angular

The framework adapts and extends traditional HTML to present dynamic


content through two-way data-binding that allows for the automatic
synchronization of models and views. As a result, Angular de-emphasizes explicit
DOM manipulation with the goal of improving testability and performance.

 The scope is the binding part between the HTML (view) and the JavaScript
(controller).
 The scope is an object with the available properties and methods.
 The scope is available for both the view and the controller.

1.5 Angular 4 vs Angular 2 vs. AngularJS

AngularJS is an open-source, JavaScript-based, front-end web application


framework for dynamic web app development. It utilizes HTML as a template
language. By extending HTML attributes with directives and binding data to
HTML with expressions, AngularJS creates an environment that is readable,
extraordinarily expressive and quick to develop.

Angular is the blanket term used to refer to Angular 2, Angular 4 and all
other versions that come after AngularJS. Both Angular 2 and 4 are open-source,
TypeScript-based front-end web application platforms.

Angular 4 is the latest version of Angular. Although Angular 2 was a


complete rewrite of AngularJS, there are no major differences between Angular 2
and Angular 4. Angular 4 is only an improvement and is backward compatible
with Angular 2.

Both Angular 2 and 4 are open-source, TypeScript-based front-end web


application platforms. Angular 4 is the latest version of Angular. Although Angular
2 was a complete rewrite of AngularJS, there are no major differences between
Angular 2 and Angular 4.

In Angular 2, controllers and $scope were replaced by components and


directives. Components are directives with a template. They deal with a view of the
application and logic on the page. There are two kinds of directives in Angular 2.
These are structural directives that alter the layout of the DOM by removing and
replacing its elements, and attributive directives that change the behavior or
appearance of a DOM element.

In Angular 4, the structural derivatives ngIf and ngFor have been improved,
and you can use if/else design syntax in your templates.

1.6 Angular 4 Environment Setup

In this chapter, we will discuss the Environment Setup required for Angular
4.

To install Angular 4, we require the following −

 Nodejs
 Npm
 Angular CLI
 IDE for writing your code

Nodejs has to be greater than 4 and npm has to be greater than 3.

Nodejs

To check if nodejs is installed on your system, type node –v in the terminal.


This will help you see the version of nodejs currently installed on your system.

C:\>node –v
v6.11.0
If it does not print anything, install nodejs on your system. To install nodejs,
go the homepage https://nodejs.org/en/download/ of nodejs and install the package
based on your OS.

The homepage of nodejs will look like the following −

Based on your OS, install the required package. Once nodejs is installed,
npm will also get installed along with it. To check if npm is installed or not, type
npm –v in the terminal. It should display the version of the npm.

C:\>npm –v
5.3.0
Angular 4 installations are very simple with the help of angular CLI. Visit
the homepage https://cli.angular.io/ of angular to get the reference of the
command.

Type npm install –g @angular/cli, to install angular cli on your system.


You will get the above installation in your terminal, once Angular CLI is
installed. You can use any IDE of your choice, i.e., WebStorm, Atom, Visual
Studio Code, etc.

1.7 Adding Angular 4 and Dependencies to Your App

Do you guys know if it's possible to add a module dependency after it's been
created? Something like that:

// init module in file A


angular.module("myApp", []);

// retrieve module in file B and add new dependencies:


mod = angular.module("myApp");
// now I want to add an 'ngResource' dependency to mod
// ???
I am working on a component based app organization and want to see if a
subcomponent can add dependencies to its parent component module without
defining its own module. Something likes that:

app/
components/
|__componentA/
|__app.js // initializes component A module
|__subcomponentA/
|__app.js // want to add subcomponentA dependencies to componentA module from here

My alternative is simply declare all subcomponent A dependencies directly


on the component A module, but from organization point of view, I'd prefer to
keep these dependencies inside the subcomponent A directory, so if I later decide
to remove the subcomponent A from the app, I don't need to remember to remove
its dependencies from the component A module. I want everything that concerns
subcomponent A to be grouped inside the subcomponent A directory. My build
script will ensure that component A code is processed before the subcomponet A
is, though.

1.8 Building Blocks of and Angular 4 Applications

Angular 4 stands on 8 building blocks following are the names and brief
explanation to it.

Modules: Modules are codes of line represented in blocks of code and they
perform various type of task. A module sends or does exports some sort of value in
the main code, such as class. When you do the study of Angular very foremost and
the most common module that you will see is the one that exports Component
Class.

export class MyAppComponent { }


Here represented in the above line of code "MyAppComponent" is a module. Since
we are discussing about Modules we would also like let you know about Libraries.

Libraries: In Angular when we add "@" at the start it becomes ‘Libraries' in short
if we add prefix like this "@angular". Modules can also be a library of other
modules. If you see within Angular 2 or Angular 4 itself has many of the modules
that are libraries of others like @angular/core is the most important library that
contains most of the modules that we need.

Components: Basically component is a class which helps to display an element on


the screen. Components consist of some properties and with that we can
manipulate how the element should look and respond on the screen. We can create
and do various activities where we can create component, destroy, and update as
per user activity done within in the application. We would like to add that Life
Cycle hooks are the modules that we use for this purpose.

export class MyCompComponent { }

Here represented in the above line of code "MyCompComponent" is a component.

Templates: It helps us to define "View" part of the Component. In simple words


Templates are basically HTML which is used to show on our page. Unlike plain
HTML, we can create angular templates which understand how to communicate
with other backing components. We can make use plain HTML tags and
component tags. These templates ultimately create DOM structure on web
browser. Data in templates is held by backing components.

Metadata: In Angular Metadata is responsible to how a class should be processed


and represented on the screen. Decorator is added ("@") to tell Angular that we are
using a component with certain metadata, we attach a decorator to it. Here
@Component will be identified as a component class. Selector tells Angular to
process the HTML that templateURL has at this tag <xxxx-xxx></xxxx-xxx>
Directives are other components that this Component will require to process and
providers are the services required. The template, metadata, and component
together describe a view. Templates and components can communicate with the
help of metadata.

Data binding: The main and powerful feature of JavaScript framework – Angular
2 or Angular 4 is data binding. Earlier version Angular 1 also supported data
binding so is the same with our new Angular 2 or Angular 4. There are 4 ways of
binding a data according to the direction to the DOM, from the DOM, or in both
directions:

<input [(ngModel)]="toy.name">
<li>{{toy.name}}</li>
<toy-detail [toy]="selectedToy"></toy-detail>
<li (click)="selectToy (toy)"></li>

 Interpolation: The {{toy.name}} interpolation display "toy.name" value with


in tag.
 Property Binding: The [toy] property binding passes the selected value of the
toy value from parent to child component.
 Event Binding: It shoots for the event when we click on the components met
hod name. The (click) event binding calls the "selectedToy" function when a
user clicks on it.
 Two-way data binding: It is a very important and the fourth way which com
bines property and event binding with the help or use of "ngModel" directive
 Directives: Directives are the ones which helps us to add behavior to the DO
M elements. They are the extension to HTML attributes. Attaching multiple
directives to the DOM elements is also possible. When using TypeScript we
define decoratives by @decorative decorator.

There are 3 types of decorative:

 Decorator Directive – As the name says it decorates (@Directive) the


elements with the help of add-on behavior. One nice example we can say that is
built-in directives like ngModel etc.
 Component Directive - It is just an extension of @Directive decorates with
template orientation based features.
 Template Directive - It does the conversion of HTML into very own
reusable template. This type of directive is as termed as Structural directive.
 Services: Angular 2 or Angular 4 service provides a function or an object
which helps to share the data and the behavior across the application. It is
JavaScript function which is used to perform a specific task. It does inclusion of
the values, function, or any other feature needed by the application. Typical
examples of services are data, logging, message service etc. Kindly note that
services do not have any no base class.

export class ToyService {


getToy(): Toy[] {
return Toy;
}
}

Dependency Injection: It is a kind of Design Pattern which is capable of passing


objects as dependencies. It does work of decoupling and removes tight coupling
with that removal of hard coded dependencies, and makes dependencies
configurable. Main benefits or purpose of using Dependency Injection is that we
can make components maintainable, reusable, and testable. It is triggered into the
Angular framework so that it can be use anywhere in an application. The injector
mainly is a technique to maintain service instance. It is created using a provider.
The provider is the way of creating a service. Registering providers along with
injectors is also possible.

1.9 A Basic Angular 4 Application


CHAPTER 2

INTRODUCTION TO TYPESCRIPT AND ES6

2.1 Programming Languages for Use with Angular

Angular 4 differs from Angular JS in regards to programming language


support. With Angular JS you generally program in JavaScript. With Angular 4 the
official site provides example code in several languages; JavaScript, TypeScript
and Dart.

JavaScript is an implementation of the ECMAScript standard. Several


versions exist including ES5 and ES6. Most current browsers fully support
JavaScript ES5. This means that code compliant with ES5 will run on most most
browsers without modification. ES6 on the other hand may not be supported and is
typically converted to ES5 before it gets to the browser. The more recent version of
JavaScript (ES6) adds features and makes certain tasks easier. It is not clear when
browsers will be fully ES6 compliant.

TypeScript and Dart are language super sets of JavaScript. This means they
include all the features of JavaScript but add many helpful features as well. But
just like the ES6 version of JavaScript they don't work on current browsers. To
work around this limitation there are utilities to convert code written in their non-
browser-compliant syntax back to JavaScript ES5. In this way they provide the
developer with advanced features and still allow code to be run on existing
browsers. The process of converting code from one language to another is referred
to as 'transpilation'. Technically this conversion is performed by a language pre-
processor that, although it does not compile anything, is commonly referred to as a
compiler.
TypeScript is an open source language that is developed and maintained by
Microsoft. It provides type safety, advanced object oriented features, and
simplified module loading. Angular 4 itself is built using TypeScript. The
documentation support is better on the Angular 2 site for TypeScript than it is for
the other options. So although you could write your Angular 4 apps in pure ES5
JavaScript you may find it more difficult and find less support if you get into
trouble than if you bite the bullet and spends some time learning TypeScript.

Dart is another alternative for programming Angular 4 applications. It is


similar in features to TypeScript and has its own loyal following. If your team is
already versed in Dart and is looking to start developing in Angular 4 it could be a
good choice. That being said, in the rest of this post, we will be concentrating on
TypeScript.

A basic Angular 2 component coded in TypeScript:

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


@Component({
selector: 'hello-app',
template: '<h1>Hello Angular 2</h1>'
})
export class AppComponent { }
2.2 TypeScript Syntax

Syntax defines a set of rules for writing programs. Every language


specification defines its own syntax. A TypeScript program is composed of −

 Modules
 Functions
 Variables
 Statements and Expressions
Comments TypeScript is a superset of JavaScript. That means any valid
JavaScript code is valid TypeScript code. But many prefer TypeScript because it
has additional features that we don’t have in the current version of JavaScript that
most browsers understand. So, when building Angular applications, we need to
have our TypeScript code converted into JavaScript code that browsers can
understand. This process is called transpilation which is the combination of
translate and compile. And that’s the job of the TypeScript compiler.

Let us start with the traditional “Hello World” example –

var message:string = "Hello World"

console.log(message)

On compiling, it will generate following JavaScript code.


//Generated by typescript 1.8.10

var message = "Hello World";

console.log(message);

Line 1 declares a variable by the name message. Variables are a


mechanism to store values in a program.

Line 2 prints the variable’s value to the prompt. Here, console refers to the
terminal window. The function log () is used to display text on the screen.

2.3 The Type System – Defining Variables

A variable, by definition, is “a named space in the memory” that stores


values. In other words, it acts as a container for values in a program. TypeScript
variables must follow the JavaScript naming rules −

 Variable names can contain alphabets and numeric digits.


 They cannot contain spaces and special characters, except the underscore (_)
and the dollar ($) sign.
 Variable names cannot begin with a digit.
 A variable must be declared before it is used. Use the var keyword to declare
variables.

Variable Declaration in TypeScript

The type syntax for declaring a variable in TypeScript is to include a colon (:) after
the variable name, followed by its type. Just as in JavaScript, we use the var
keyword to declare a variable.

When you declare a variable, you have four options −

1. Declare its type and value in one statement.

2. Declare its type but no value. In this case, the variable will be set to
undefined.

3. Declare its value but no type. The variable type will be set to any.

4. Declare neither value not type. In this case, the data type of the variable will
be any and will be initialized to undefined.
The following table illustrates the valid syntax for variable declaration as discussed
above –

Example: Variables in TypeScript

var name:string = "John";

var score1:number = 50;

var score2:number = 42.50

var sum = score1 + score2

console.log("name"+name)

console.log("first score: "+score1)

console.log("second score: "+score2)

console.log("sum of the scores: "+sum)

On compiling, it will generate following JavaScript code.


//Generated by typescript 1.8.10
var name = "John";

var score1 = 50;

var score2 = 42.50;

var sum = score1 + score2;

console.log("name" + name);

console.log("first score: " + score1);

console.log("second score : " + score2);

console.log("sum of the scores: " + sum);

The output of the above program is given below −


name:John
first score:50
second score:42.50
sum of the scores:92.50

The TypeScript compiler will generate errors, if we attempt to assign a value to a


variable that is not of the same type. Hence, TypeScript follows Strong Typing.
The Strong typing syntax ensures that the types specified on either side of the
assignment operator (=) are the same. This is why the following code will result in
a compilation error −

var num:number = "hello" // will result in a compilation error

2.4 The Type System – Defining Arrays

The use of variables to store values poses the following limitations −

 Variables are scalar in nature. In other words, a variable declaration can only
contain a single at a time. This means that to store n values in a program n variable
declarations will be needed. Hence, the use of variables is not feasible when one
needs to store a larger collection of values.
 Variables in a program are allocated memory in random order, thereby
making it difficult to retrieve/read the values in the order of their declaration.

TypeScript introduces the concept of arrays to tackle the same. An array is a


homogenous collection of values. To simplify, an array is a collection of values of
the same data type. It is a user defined type.

Features of an Array

Here is a list of the features of an array −

 An array declaration allocates sequential memory blocks.


 Arrays are static. This means that an array once initialized cannot be resized.
 Each memory block represents an array element.
 Array elements are identified by a unique integer called as the subscript /
index of the element.
 Like variables, arrays too, should be declared before they are used. Use the
var keyword to declare an array.
 Array initialization refers to populating the array elements.
 Array element values can be updated or modified but cannot be deleted.

Declaring and Initializing Arrays

To declare an initialize an array in Typescript use the following syntax −

Syntax

var array_name[:datatype]; //declaration


array_name = [val1,val2,valn..] //initialization
An array declaration without the data type is deemed to be of the type any. The
type of such an array is inferred from the data type of the array’s first element
during initialization.

For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an


array as given below −

The array pointer refers to the first element by default.

Arrays may be declared and initialized in a single statement. The syntax for the
same is –

var array_name[:data type] = [val1,val2…valn]

Note − The pair of [] is called the dimension of the array.


Accessing Array Elements
The array name followed by the subscript is used refer to an array element. Its
syntax is as follows −
array_name[subscript] = value

2.5 The Type System – Classes & Objects

TypeScript is object oriented JavaScript. TypeScript supports object-


oriented programming features like classes, interfaces, etc. A class in terms of
OOP is a blueprint for creating objects. A class encapsulates data for the object.
Typescript gives built in support for this concept called class. JavaScript ES5 or
earlier didn’t support classes. Typescript gets this feature from ES6.

Creating classes

Use the class keyword to declare a class in TypeScript. The syntax for the same is
given below −

Syntax

class class_name {
//class scope
}
The class keyword is followed by the class name. The rules for identifiers must be
considered while naming a class.

A class definition can include the following −

Fields − A field is any variable declared in a class. Fields represent data pertaining
to objects

Constructors − Responsible for allocating memory for the objects of the class

Functions − Functions represent actions an object can take. They are also at times
referred to as methods

These components put together are termed as the data members of the class.

Consider a class Person in typescript.

class Person {

On compiling, it will generate following JavaScript code.


//Generated by typescript 1.8.10

var Person = (function () {

function Person() {

return Person;

}());

Example: Declaring a class

class Car {

//field

engine:string;

//constructor

constructor(engine:string) {

this.engine = engine

//function

disp():void {

console.log("Engine is : "+this.engine)

The example declares a class Car. The class has a field named engine. The
var keyword is not used while declaring a field. The example above declares a
constructor for the class.

A constructor is a special function of the class that is responsible for


initializing the variables of the class. TypeScript defines a constructor using the
constructor keyword. A constructor is a function and hence can be parameterized.
The this keyword refers to the current instance of the class. Here, the
parameter name and the name of the class’s field are the same. Hence to avoid
ambiguity, the class’s field is prefixed with the this keyword.

disp() is a simple function definition. Note that the function keyword is not
used here.

On compiling, it will generate following JavaScript code.

//Generated by typescript 1.8.10

var Car = (function () {

//constructor

function Car(engine) {

this.engine = engine;

//function

Car.prototype.disp = function () {

console.log("Engine is : " + this.engine);

};

return Car;

}());

Object

An object is an instance which contains set of key value pairs. The values can be
scalar values or functions or even array of other objects. The syntax is given below

Syntax
var object_name = {
key1: “value1”, //scalar value
key2: “value”,
key3: function() {
//functions
},
key4:[“content1”, “content2”] //collection
};

As shown above, an object can contain scalar values, functions and


structures like arrays and tuples.

Example: Object Literal Notation

var person = {

firstname:"Tom",

lastname:"Hanks"

};

//access the object values

console.log(person.firstname)

console.log(person.lastname)

On compiling, it will generate the same code in JavaScript.


The output of the above code is as follows −
Tom
Hanks

2.6 Class Constructors

2.7 Class Constructors – Alternate Form

2.8 Interfaces

2.9 Parameter and Return Value Types

2.10 Working with Modules


2.11 TypeScript Transpilation

2.12 Arrow Functions

2.13 Template Strings

2.14 Template Strings – Variables and Expressions

2.15 Template Strings – Multiline

2.16 Generics – Class

2.17 Generics – Methods

2.18 Generics – Restricting Types

CHAPTER 3

COMPONENTS IN ANGULAR 4

3.1 What is a Component?

3.2 An Example Component

3.3 Component Starter

3.4 Developing a Simple Login Component

3.5 Login Component: Add HTML

3.6 The HTML Component Template

3.7 Login Component

3.8 Component Decorator Properties


3.9 Component Lifecycle Hooks

3.10 Using a Lifecycle Hook: OnInit

CHAPTER 4

DATA AND EVENT BINDING

4.1 Binding Syntax

4.2 One-Way Output Binding

4.3 Binding Displayed Output Values

4.4 Two-Way Binding of Input Fields

Data-binding is probably the coolest and most useful feature in Angular 4. It


will save you from writing a considerable amount of boilerplate code. A typical
web application may contain up to 80% of its code base, dedicated to traversing,
manipulating, and listening to the DOM. Data-binding makes this code disappear,
so you can focus on your application.

Think of your model as the single-source-of-truth for your application. Your


model is where you go to to read or update anything in your application. The data-
binding directives provide a projection of your model to the application view. This
projection is seamless, and occurs without any effort from you.

Traditionally, when the model changes, the developer is responsible for


manually manipulating the DOM elements and attributes to reflect these changes.
This is a two-way street. In one direction, the model changes drive change in DOM
elements. In the other, DOM element changes necessitate changes in the model.
This is further complicated by user interaction, since the developer is then
responsible for interpreting the interactions, merging them into a model, and
updating the view. This is a very manual and cumbersome process, which becomes
difficult to control, as an application grows in size and complexity.

There must be a better way! Angular4' two-way data-binding handles the


synchronization between the DOM and the model, and vice versa.

4.5 Input Binding Examples

Here is a simple example, which demonstrates how to bind an input value to


an <h1> element.

<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/angular-
1.0.0rc10.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name
here">
<hr>
<h1>Hello, {{yourName}}!</h1>
</div>
</body>
</html>
4.6 Binding Events

In this chapter, we will discuss how Event Binding works in Angular 4.


When a user interacts with an application in the form of a keyboard movement, a
mouse click, or a mouseover, it generates an event. These events need to be
handled to perform some kind of action. This is where event binding comes into
picture.

4.7 Binding Events Examples

Let us consider an example to understand this better.

app.component.html
<!--The content below is only a placeholder and can be replaced.-->

<div style = "text-align:center">

<h1>

Welcome to {{title}}.

</h1>

</div>

<div> Months :

<select>

<option *ngFor = "let i of months">{{i}}</option>

</select>

</div>

<br/>

<div>

<span *ngIf = "isavailable; then condition1 else condition2">

Condition is valid.

</span>

<ng-template #condition1>Condition is valid</ng-template>

<ng-template #condition2>Condition is invalid</ng-template>

</div>

<button (click)="myClickFunction($event)">

Click Me

</button>

In the app.component.html file, we have defined a button and added a function to it


using the click event.

Following is the syntax to define a button and add a function to it.

(click)="myClickFunction($event)"

The function is defined in the .ts file: app.component.ts


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

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

title = 'Angular 4 Project!';

//array of months.

months = ["January", "Feburary", "March", "April",

"May", "June", "July", "August", "September",

"October", "November", "December"];

isavailable = true;

myClickFunction(event) {

//just added console.log which will display the event details in browser on
click of the button.

alert("Button is clicked");

console.log(event);

Upon clicking the button, the control will come to the function myClickFunction
and a dialog box will appear, which displays the Button is clicked as shown in the
following screenshot –
4.8 Setting Element Properties

4.9 Setting Properties: Examples

CHAPTER 5

ATTRIBUTE DIRECTIVES AND PROPERTY BINDINGS

5.1 What are Directives

5.2 Directive Types

5.3 Apply Styles by Changing Classes

5.4 Changing Classes – Example

5.5 Applying Styles Directly

5.6 Applying Styles Directly – Example

5.7 Obsolete Directives and Property Binding

5.8 Controlling Element Visibility

5.9 Setting Image Source Dynamically

5.10 Setting Hyperlink Source Dynamically


CHAPTER 6

STRUCTURAL DIRECTIVES

6.1 Structural Directives

A structure directive basically deals with manipulating the dom elements.


Structural directives have a * sign before the directive. For example, *ngIf and
*ngFor.

6.2 Adding and Removing Elements Dynamically

6.3 Looping Using ngFor

6.4 ngFor – Basic Syntax

6.5 ngFor – Full Template Syntax

6.6 Creating Tables with ngFor

6.7 ngFor Local Variables

6.8 ngFor Changes in the backing data source

6.9 Swapping Elements with ngSwitch

6.10 ngSwitch – Basic Syntax

6.11 ngSwitch – Full Template Syntax


CHAPTER 7

TEMPLATE DRIVEN FORMS

7.1 Template Driven Forms

With a template driven form, most of the work is done in the template; and
with the model driven form, most of the work is done in the component class.

Let us now consider working on the Template driven form. We will create a
simple login form and add the email id, password and submit the button in the
form. To start with, we need to import to FormsModule from @angular/core which
is done in app.module.ts as follows –

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

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

import { RouterModule} from '@angular/router';

import { HttpModule } from '@angular/http';

import { FormsModule } from '@angular/forms';

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

import { MyserviceService } from './myservice.service';

import { NewCmpComponent } from './new-cmp/new-cmp.component';

import { ChangeTextDirective } from './change-text.directive';

import { SqrtPipe } from './app.sqrt';

@NgModule({

declarations: [

SqrtPipe,

AppComponent,
NewCmpComponent,

ChangeTextDirective

],

imports: [

BrowserModule,

HttpModule,

FormsModule,

RouterModule.forRoot([

{path: 'new-cmp',component: NewCmpComponent}

])

],

providers: [MyserviceService],

bootstrap: [AppComponent]

})

export class AppModule { }

So in app.module.ts, we have imported the FormsModule and the same is added in


the imports array as shown in the highlighted code.

Let us now create our form in the app.component.html file.

<form #userlogin = "ngForm" (ngSubmit) = "onClickSubmit(userlogin.value)" >


<input type = "text" name = "emailid" placeholder = "emailid" ngModel>
<br/>
<input type = "password" name = "passwd" placeholder = "passwd" ngModel>
<br/>
<input type = "submit" value = "submit">
</form>

We have created a simple form with input tags having email id, password
and the submit button. We have assigned type, name, and placeholder to it.
In template driven forms, we need to create the model form controls by adding the
ngModel directive and the name attribute.
Thus, wherever we want Angular to access our data from forms, add
ngModel to that tag as shown above. Now, if we have to read the emailid and
passwd, we need to add the ngModel across it.
If you see, we have also added the ngForm to the #userlogin. The ngForm directive
needs to be added to the form template that we have created. We have also added
function onClickSubmit and assigned userlogin.value to it.
Let us now create the function in the app.component.ts and fetch the values
entered in the form.

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

import { MyserviceService } from './myservice.service';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

title = 'Angular 4 Project!';

todaydate;

componentproperty;

constructor(private myservice: MyserviceService) { }

ngOnInit() {

this.todaydate = this.myservice.showTodayDate();

onClickSubmit(data) {

alert("Entered Email id : " + data.emailid);

}
In the above app.component.ts file, we have defined the function
onClickSubmit. When you click on the form submit button, the control will come
to the above function.

This is how the browser is displayed –

The form looks like as shown below. Let us enter the data in it and in the
submit function, the email id is already entered.

The email id is displayed at the bottom as shown in the above diagram.

7.2 Note on Deprecated Forms APIs

7.3 A Basic Angular Form

7.4 Binding Input Fields

7.5 Accessing the Form Object

7.6 Binding the Form Submit Event

7.7 The Submit Function

7.8 Basic HTML5 Validation – “required” Attribute


7.9 HTML5 vs. Angular Validation

7.10 Angular Validation

7.11 Displaying Form Validation State

7.12 Displaying Field Validation State

7.13 Displaying Validation State Using Classes

7.14 Disabling Submit when Form is Invalid

7.15 Submitting the Form

7.16 Binding to Object Variables

7.17 Additional Input Types

7.18 Checkboxes

7.19 Select(drop down) Fields

7.20 Rendering Options for Select (drop down)

7.21 Date fields

7.22 Radio Buttons

CHAPTER 8

SERVICE AND DEPENDENCY INJECTION

8.1 What is a Service?

8.2 Creating a Basic Service

8.3 What is Dependency Injection?

8.4 What Dependency Injection Looks Like

8.5 Injecting Services

8.6 Using a Service in a Component: Dedicated Instance

8.7 Using onInit to Initialize Component Data


8.8 Using a Shared Service Instance

8.9 Dependency Injection

CHAPTER 9

HTTP CLIENT

9.1 The Angular HTTP Client

9.2 Using The HTTP Client – Overview

9.3 Setting up the Root Component

9.4 Service Using Http Client

9.5 Importing Individual HTTP Providers into Services

9.6 Service Imports

9.7 The Observable object type

9.8 What does an Observable Object do?

9.9 Making a Basic HTTP GET Call

9.10 Using the Service in a Component

9.11 The Component

9.12 Component Code Review

9.13 Importing Observable Methods

9.14 Enhancing the Service with .map() and .catch()

9.15 Using .map()

9.16 Using .catch()

9.17 Using toPromise()


9.18 GET Request

9.19 GET Request with Options

9.20 POST Request

9.21 Reading HTTP Response Headers

CHAPTER 10

PIPES AND DATA FORMATTING

10.1 What are Pipes?


10.2 More on Pipes
10.3 Formatting Changes in Angular 4
10.4 Using a Built-in Pipe
10.5 Built-In Pipes
10.6 Using Pipes in HTML
10.7 Chaining Pipes
10.8 Using Pipes in JavaScript
10.9 Some Pipe Examples
10.10 Decimal Pipe
10.11 CurrencyPipe
10.12 Custom Pipes
10.13 Custom Pipe Example
10.14 Using Custom Pipes
10.15 A Filter Pipe
10.16 A Sort Pipe
10.17 Pipe Category: Pure and Impure
10.18 Pure Pipe Example
10.19 Impure Pipe Example
CHAPTER 11

INTRODUCTION TO SINGLE PAGE APPLICATION

11.1 What is a Single Page Application (SPA)


11.2 SPA Workflow
11.3 Traditional Web Application Capabilities
11.4 Single Page Application Advantages
11.5 SPA and Traditional Web Sites
11.6 SPA Challenges
11.7 Implementing SPA’s Using Angular 4
11.8 Simple SPA Using Visibility Control
11.9 SPA Using Angular Components
11.10 SPA with Angular Components – Switching
11.11 SPA with Angular Components – The Displayed Component
11.12 Implement SPA Using an Angular Component Router

CHAPTER 12

THE ANGULAR COMPONENT ROUTER

12.1 Routing and Navigation


12.2 The Component Router
12.3 Traditional Browser Navigation
12.4 Component Router Terminology
12.5 Setting up the Component Router
12.6 Local URL Links
12.7 Browser pushState
12.8 Routes
12.9 The app.routes.ts File
12.10 The app.routes.ts File – Example
12.11 Bootstrapping Routing in Main.ts
12.12 A Basic App With Routing
12.13 App Routes
12.14 AppComponent – Code
12.15 AppComponent – Router Related Features
12.16 AppComponent – precompile array
12.17 AppComponent – routerLinks
12.18 Programmatic Navigation
12.19 Basic Navigation
12.20 Passing Data During Navigation
12.21 Creating Routes with Route Parameters
12.22 Navigating with Route Parameters
12.23 Using Route Parameter Values
12.24 Retrieving the Route Parameter Synchronously
12.25 Retrieving a Route Parameter Asynchronously
12.26 Query Parameters
12.27 Query Parameters – Example Component
12.28 Query Parameters – queryParams
12.29 Query Parameters – Navigation
12.30 Retrieving Query Parameters Asynchronously
12.31 Problems with Manual URL entry and Bookmarking
12.32 Fixing Manual URL entry and Bookmarking

You might also like