0% found this document useful (0 votes)
10 views

Cloud computing unit 5

Note of cloud computing

Uploaded by

Jayasri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Cloud computing unit 5

Note of cloud computing

Uploaded by

Jayasri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT IV

EXPRESS AND ANGULAR

Implementing Express in Node.js - Configuring routes - Using Request and Response objects
- Angular - Typescript - Angular Components - Expressions - Data binding - Built-in
directives

I. Implementing Express in Node.js


Express:
• Express refers to Express.js, a minimal and flexible Node.js web application
framework.
• It is used to build web applications and APIs quickly and efficiently. It simplifies the
process of building server-side web applications and APIs by providing robust tools and
features. Express is commonly used in full-stack JavaScript development because it
allows developers to manage routing, request handling, and middleware in a
streamlined way.
• Express is a part of the MEAN (MongoDB, Express.js, Angular, Node.js) and MERN
(MongoDB, Express.js, React, Node.js) stacks, which are popular JavaScript-based
full-stack development technologies.
how Express fits in the full-stack environment:
1.Server-Side Framework: Express is used on the back-end .
It manages the routing (handling URLs and HTTP requests), middleware (handling processes
like authentication, validation, etc.), and communication between the client and the database.
2.Handling Requests and Responses: to define how the application should respond to
different HTTP requests (GET, POST, PUT, DELETE).
3.Middleware Support: to perform various tasks like parsing request bodies, managing
cookies, logging requests, etc.
4.RESTful APIs: Express is often used to create RESTful APIs, allowing the front-end (React,
Angular) to communicate with the back-end server.
Getting Started with Express:
Prerequisites:
Node.js: Express.js is built on Node.js, so need Node.js installed.
Basic JavaScript knowledge: Express.js uses JavaScript for server-side scripting.
• Add the express module
1
npm install express
• Create an instance class to act as the http server for node.js application.
var express=require(‘express’)
var app=express()
• express = require('express'): Imports the Express.js library.
• app = express(): Creates an Express application instance, which you will use to handle
requests and responses.
Configuring express Settings:
• It defines the environment as well as how express handles JSON parsing routing and views.
Methods to see the value of the application settings:
1. set(setting, value)
• →used to configure settings in Express application.
• →It allows the developer to control the behavior of various aspects of the app, such as view
rendering, request handling, and response formatting.

Common Settings:
• view engine: Specifies the template engine (e.g., Pug, EJS).
• case sensitive routing: When set to true, /Home and /home are treated as different routes.
2. Enable(setting)
• to set a specific setting to true.
• This function is used to enable a specific setting or configuration option within the
application. This method allows to control various behaviors of the Express server.
• It’s typically used for Boolean settings that either enable or disable a feature.
• It can be thought of as equivalent to app.set(setting, true).

3. Disable(setting)
• It is a shortcut to set a specific setting to false.
• It disables a feature and can be seen as equivalent to app.set(setting, false).

2
Starting the Express server:
To begin implementing Express as the HTTP server for your Node.js application,
• need to create an instance and begin listening on a port.
var express = require('express’);
var app = express();
app.listen(8080);

• This tells the Express application to listen for incoming requests on port 8080.
• The listen() method takes a port number as its argument, and here it is set to 8080.
When the server is running, it listens for HTTP requests on http://localhost:8080.

var express = require('express');


var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
host: '127.0.0.1’,
key: fs.readFileSync('ssl/server.key’),
cert: fs.readFileSync('ssl/server.crt')
};
http.createServer (app).listen(80);
https.createServer (options, app).listen(443);
app.get('/', function(req, res) {
res.send('Hello from Express');
});

• host: '127.0.0.1': specifies that the server will be accessible only from the local machine
(localhost).
• key: fs.readFileSync('ssl/server.key'): reads the private key file (server.key) from the ssl/
directory. The key is required for establishing a secure HTTPS connection.
• cert: fs.readFileSync('ssl/server.crt'): reads the certificate file (server.crt) from the ssl/
directory. The certificate is also required for HTTPS and verifies the server's identity.
• Both the key and cert files are necessary for SSL/TLS communication, which ensures encrypted
and secure transmission between the server and clients.

3
• http.createServer(app).listen(80); creates an HTTP server using the http module and binds it
to port 80. Port 80 is the default port for HTTP (unsecured) traffic.
• The app instance (the Express application) handles incoming HTTP requests on port 80.
• https.createServer(options, app).listen(443);creates an HTTPS server using the https module
and the options object containing the SSL/TLS certificate and key.
• It listens on port 443, which is the default port for HTTPS (secure) traffic.
• GET route on the root URL (/). When a client makes a GET request to http://localhost/ (or
https://localhost/), the server responds with the message "Hello from Express".

II. CONGIGURING ROUTES

• Before the server can begin accepting requests, its need to define the routes.
• In Express.js, configuring routes is essential for defining how your application responds to
different HTTP requests (like GET, POST, PUT, DELETE). Routes specify which functions
are executed when the app receives a request to a particular URL or endpoint.

• Route describes how to handle the path portion of the URL in the http request to the express
server.
Implementing Routes:
Two parts: when defining the route
1. HTTP request method(GET or POST)
2. the path specified in the URL
functions used to implement routes for the Express server.
Syntax:
app. <method> (path, [callback .1, callback)
The <method> portion refers to the HTTP request method, such as GET or POST.
For example:
app.get(path, [middleware, ...), callback)
app.post (path, (middleware,...), callback)

• path refers to the path portion of the URL that you want to be handled by the callback function.

• Middleware parameter applied before executing the callback function

4
• Callback function is the request handler that handles the request and sends the response back to
the client.

• The callback function accepts a request object as the first parameter and a response object as the
second.

• When the express server receives an http request , it looks for a route that has been defined for the
appropriate HTTP method and path.
app.get('/’, function(req, res) {
res.send('Hello, World!’);
});
app.get('/about’, function(req, res) {
res.send('This is the About page.’);
});
app.post('/submit’, function(req, res) {
res.send('Data submitted successfully!’);
});

• app.get(): Defines a route handler for HTTP GET requests to the /about path.
• '/about': This is the route or endpoint. When a user visits http://yourserver.com/about, this
function will handle the request.

• function (req, res): This is the callback function that is executed when the /about route is hit.
It takes two parameters:
• req (request): Represents the incoming HTTP request.

• res (response): Represents the outgoing HTTP response


• res.send('This is the About page.'): Sends a response with the message "This is the About
page." back to the client.

• app.get() is used for handling HTTP GET requests, which are typically used for retrieving data
from the server.

• app.post() is used for handling HTTP POST requests, which are typically used for sending
data to the server (such as form submissions).

• app.all() works the same as app.post() and app.get(). Here the call back function for app.all()
is called for every request for the specified path.
5
app.all(‘*’,function(req,res){
// global handler for all paths
});
Applying parameters in routes:

• several ways to pass parameters to routes, which can be useful for retrieving data, processing
user input, and more.

• Each method allows different types of data to be included in the request.


1. Query String Parameters
• This is commonly used for filtering, sorting, or sending small amounts of data.

• Starts with: A ? symbol that marks the beginning of the query string in the URL.
• Key-value pairs: Parameters are expressed as key-value pairs separated by the = symbol.
• Multiple parameters: Multiple key-value pairs are separated by &.
app.get('/find', function(req, res) {
var url_parts= url.parse(req.url, true);
var query = url_parts.query;
res.send('Finding Book: Author: ' + query.author +’Title: ‘+ query.title);
});
Example:
http://localhost:3000/find?author=John&title=AI
Query Parameters:
• author=John
• title=AI
Response: The server will respond with the text
Finding Book: Author: John Title: AI
This route handler processes a URL with query parameters (?author=John&title=AI), parses
the query string to extract the parameters, and sends back a response that displays the values
of author and title.
2. Regex Parameters:
6
In Express.js ,It can define routes with regular expressions (regex) to match more
complex patterns in the URL. This is useful when it needs more flexibility in routing, such as
matching dynamic segments of a URL or enforcing specific formats.
app.get(/^\/book\/(\w+)\:(\w+)?$/, function(req, res) {
res.send('Get Book: Chapter: + req.params [0] +
'Page: ' + req.params[1]);
});
example, consider the following URL:
/book/12:15
The res.send() method returns
Get Book: Chapter: 12 Page: 15
3. Route parameters using Defined parameters:

• Route parameters are dynamic segments in a URL defined by a colon (:) followed by a name.
• These parameters are part of the URL path and can be accessed using req.params.

Example:
app.get('/user/:id', function(req, res) {
const userId = req.params.id; // Access the route parameter 'id'
res.send('User ID: ' + userId);
});
• URL Request: /user/123
• Route Parameter: id
• Extracted Value: 123 → res.send() method returns Get user: 123

4. Applying callback function for defined parameters


When parsing the URL if Express finds a parameter that has a callback registered it
calls the parameter’s callback function before calling the route handler. More than one call back
function can be registered for a route.
app.param() method is used to register a callback function. It accepts the defined
parameter as the first argument and then a callback function that receives the request , response ,
next and value parameter.
app.param(param,function(req,res,next,vakue){});

7
Example:
app.param('userid', function(req, res, next, value) {
console.log("Request with userid: + value);
next();
});
consider the following URL:
/user/4983
The userid of 4983 is parsed from the URL and the consol.log() statement displays
Request with userid: 4983
III. Using Request and Response objects
In Express.js, the Request (req) and Response (res) objects are key components of
handling incoming HTTP requests and sending responses back to clients. These objects are passed
as arguments to callback functions in route handlers and provide numerous methods and properties
to handle various aspects of web requests and responses.
Request Object (req)
The Request object contains data about the incoming HTTP request, such as the URL,
query parameters, route parameters, body data, headers, and more.
Key Properties and Methods of req:
• req.params: Contains route parameters (captured from dynamic parts of the route).
• req.query: Contains query string parameters from the URL.
• req.body: Contains the body data (useful for POST, PUT, PATCH requests, with middleware
like body-parser).
• req.headers: Contains the HTTP headers sent by the client.
• req.url: The full URL of the incoming request.
• req.method: The HTTP method used for the request (GET, POST, etc.).
• req.path: The path portion of the URL.
• req.cookies: Contains cookies sent by the client (requires cookie-parser middleware).
• req.ip: The IP address of the client.

Example:

01 var express== require('express');

02 var app express();

03 app.listen(80);
8
04 app.get('/user/:userid', function (req, res) {

05 console.log ("URL:\t “+req.originalurl);

06 console.log ("Protocol: "+req.protocol);

07 console.log ("IP:\t “+req.ip);

08 console.log ("Path:\t”+ req.path);


9
Response Object
The Response object is used to send a response back to the client. It provides methods to send
data, set headers, manage response status codes, redirect requests, and more.
Key Properties and Methods of res:
• res.send(): Sends a response to the client. The response can be a string, JSON, buffer, or
HTML.
• res.json(): Sends a JSON response.

10
• res.status(): Sets the HTTP status code for the response (e.g., 200, 404, 500).
• res.redirect(): Redirects the client to another URL.
• res.render(): Renders a view template (useful when working with templating engines like
Pug or EJS).
• res.set(): Sets a specific response header.
• res.cookie(): Sets a cookie (requires cookie-parser middleware).
• res.end(): Ends the response without any data (useful when you want to just terminate the
connection).
Setting Header:
In Express.js, it can set response headers using the Response (res) object. Headers provide meta-
information about the response and are typically used to control caching, content type, encoding,
and other details. The headers must be set before sending the response body to the client.

Setting the status:


The status code in an HTTP response indicates the outcome of the request—whether it succeeded,
encountered an error, or something else.
The .status() method on the response (res) object is used to set this status code in Express. This
method is chained to other methods like .send() or .json(), which send the response body back to
the client. By explicitly setting the status code, you provide a clear and standardized way for clients
to interpret the result of their requests.

11
Example status codes include:
• res.status(200) //200 for successful requests (OK)
• res.status(400) //400 for client errors (Bad Request)
• res.status(404) //404 for resources not found (Not Found)
• res.status(500) //500 for server errors (Internal Server Error)

Sending JSON Data:


Express facilitates sending JSON by providing the json() and jsonp() methods on the Response
object. These methods use a similar syntax as send () except that the body is a JSON stringifiable
JavaScript object:
res.json(status, [object])
res.json([body])
res.jsonp(status, [object))
res.jsonp([object])
Example:
app.get('/user/:id', function(req, res) {
const userId = req.params.id;
// Sending JSON response
res.status(200).json({
id: userId,
message: 'User details retrieved successfully'
});
});
Redirecting to Another URL:
In Express.js, redirecting is a common practice when you want to send users from one route to
another. This can happen when URLs change, after a successful form submission, or as part of a
login/logout flow. The res.redirect() method is used to send a client to a new URL, either
temporarily or permanently.
Syntax:
app.get('/old-route', function(req, res) {
// Redirect the client to a new route
12
res.redirect('/new-route');
});
IV. Angular
Angular is a popular open-source web application framework maintained by Google.
It's designed for building dynamic, single-page applications (SPAs) with a focus on code
modularity, testability, and maintainability. Angular uses a component-based architecture, where
each component represents a part of the user interface (UI) that can be reused across the application.

Typescript:
• Angular and TypeScript form a powerful combination for building scalable, maintainable
web applications.
• Angular is a popular framework for building single-page applications (SPAs), while
TypeScript, a statically typed superset of JavaScript, serves as the programming language
used to write Angular applications.
Different Types
TypeScript provides a rich set of types, which allow developers to explicitly define and enforce the
kind of data variables, functions, and objects can hold.
1.string: Represents textual data.
Example:
var mystring: string=’some text’;
2. number: Represents numerical values, both integers and floating points.
var age: number = 25;
3. boolean: Represents a true/false value.
var yes: boolean=true;
var no:boolean=false;
4. Array Type: An indexed array is a series of separate distinct data items. It can be defined
using two syntaxes:

13
5. NULL: Represents an explicitly set null value and represents the intentional absence of any
value.
Using null is better than assigning a value of o or an empty string (“ “) because those may be valid
values for the variable. By assigning null to a variable, can assign no value and check against null
inside the code, like this:
var newvar = var;
6.Any: Allows any type of value (disables type-checking).
Var anyType: any "String Assigned";
Var anyType = 404;
Var anyType = True;

7.void: Represents the absence of a value, commonly used for functions that don’t return a value
void is used when declaring a function, don't want to have a return value. The example is a
function of type void:
function empty(): void {document.write("code goes here");}
8.Enum: Enums allow you to define a set of named constant values.
enum Direction {
Up,
Down,
Left,
Right }
var x=Direction.Up // var x equal to the number 0
var y= Direction[0] // var y equal to the string up
Understanding Interfaces:
Interfaces in TypeScript are a powerful way to define the structure of an object or class.
They serve as contracts that enforce the shape, properties, and types that an object or class should
adhere to. Interfaces allow TypeScript to catch errors early, as they ensure that the implementing
objects or classes follow the expected structure.
Keyword interface is used followed by the structure that objects to follow
Example:

14
interface person {
name: string;
age: number;
}
var user: Person = { name: "Alice", age: 25, };
• The Person interface defines the structure for a person object, which must have a name
property of type string and an age property of type number.
• The user variable must conform to this structure to avoid type errors.

Implementing classes:
Classes in TypeScript are blueprints for creating objects. They encapsulate data
(properties) and behavior (methods) within a structured unit. TypeScript classes are similar to classes
in other object-oriented programming languages, but with added support for type checking and
interfaces.
In TypeScript, classes are enhanced by features like inheritance, access modifiers (such
as private, protected, and public), interfaces, and more, making them powerful tools for building
scalable, maintainable applications.
Class Basics
A class in TypeScript is defined using the class keyword, followed by the class name
and a set of properties and methods inside its body.
A basic class has a constructor method that initializes its properties, and you can add
other methods to define the class’s behavior.
Example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}

15
}
const person1 = new Person("Alice", 25);
person1.greet(); // Output: Hello, my name is Alice and I am 25 years old.
• The Person class has two properties: name and age, both defined with specific types.
• The constructor is used to initialize these properties when a new Person object is created.
• The greet method defines a behaviour that logs a message to the console.
Class Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a class (called a subclass or child class) to inherit properties and methods from another
class (called a superclass or parent class). Inheritance promotes code reuse, allowing developers
to create new classes based on existing ones while adding or modifying specific functionalities.
In TypeScript, inheritance is implemented using the extends keyword. The child class
can access public and protected members of the parent class and can also override methods to
provide specialized behavior.
Key Concepts of Class Inheritance
1. Base Class (Parent Class): The class from which properties and methods are inherited.
2. Derived Class (Child Class): The class that inherits from the base class. It can extend
or override the properties and methods of the base class.
3. Constructor Chaining: The child class can call the parent class's constructor using the
super() function.
Example:
// Base Class
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(`${this.name} makes a noise.`);
}
}
16
// Derived Class
class Dog extends Animal {
constructor(name: string) {
super(name); // Call the constructor of the parent class
}
speak(): void {
console.log(`${this.name} barks.`);
}
}
// Creating an instance of the derived class
const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
• Animal is the base class, which has a property name and a method speak().
• Dog is a derived class that extends Animal. It overrides the speak() method to provide a
specific implementation for dogs.
• The super(name) call in the Dog constructor invokes the constructor of the Animal class
to initialize the name property.

Implementing Modules:
Modules in TypeScript are a way to organize and encapsulate code. It is used to split
the application into separate, manageable parts that can be imported and exported as needed.
This enhances code reusability, maintainability, and collaboration among developers.
Key Concepts of TypeScript Modules
1. Module Declaration: Any TypeScript file can be treated as a module if it contains at
least one import or export statement. This makes the file a separate scope for variables
and functions.
2. Exporting Modules: You can export variables, functions, classes, or interfaces from a
module so they can be used in other modules.
3. Importing Modules: You can import exported members from other modules to use
them in your current module.

17
The following example splits the person class into two separate modules:
module Person {
export interface PersonInterface {
name: string;
hungry: boolean)
feed():
}
}
/// <reference path "Person.te" />
module Person{
export class Person implements PersonInterface {
name: string;
age: number;
hungry: boolean true;
constructor (name: string, age?: number) {
this.name =name;
this.age= age;
}
feed() {
this.hungry= false;
return 'Yummy!';
}
}
}
var Brendan =newPerson("Brendan", 21);
In this example, the root module has the interface for Person. The submodule starts by using
/// <reference path="Person.ts" /> to point to the root module so it can have access to the
PersonInterface interface. The example then proceeds to build the Person class submodule.
18
Understanding Functions:
Functions are fundamental building blocks in TypeScript (and JavaScript) that is used
to encapsulate reusable code and define a set of instructions that can be executed whenever
needed, providing structure and modularity to your code.
Key Concepts of Functions
1. Function Declaration: The basic way to define a function.
2. Function Expression: Functions can be defined as expressions and assigned to
variables.
3. Arrow Functions: A more concise syntax for writing functions, introduced in ES6.
4. Parameters and Arguments: Functions can accept inputs (parameters) and return outputs
(results).
5. Return Types: You can specify the type of value that a function returns.
6. Optional and Default Parameters: Functions can have optional parameters and
parameters with default values.
7. Rest Parameters: A way to handle an indefinite number of arguments as an array.
8. Function Overloading: Allowing functions to have multiple signatures.
Example:
function hello(x: string, y: string): string{
Return x+’ ‘+ y;
}

V.Angular Components
A component in Angular is a key building block of an Angular application. It is a
reusable unit of an Angular application formed by a template and a class that controls a section
of the screen.
The class includes attributes and methods that describe the component’s behavior, while
the template determines the component’s structure and appearance on the screen.

19
Components are used to divide a huge application into smaller, more manageable, and
self-contained components. They communicate with one another via inputs, outputs, and
services, resulting in a more modular and easy-to-maintain application.

Each component consists of:


• HTML template: Defines the structure of the view.
• TypeScript class: Handles the logic and data for the component.
• CSS styles: Defines the styling for the view (optional).
Structure of an Angular Component
An Angular component is made up of four key parts:
1. Decorator: A special TypeScript syntax that provides metadata about the component.
2. Template: The HTML structure of the view that defines how the component will
render on the screen.
3. Class: The TypeScript logic of the component that handles data and events.
4. Styles: Optional CSS to style the view.
Example:
// app.component.ts (Class)
import { Component } from '@angular/core';

@Component({
20
selector: 'app-root', // The HTML tag to use in templates
templateUrl: './app.component.html', // Path to the HTML template
styleUrls: ['./app.component.css'] // Path to the CSS styles
})
export class AppComponent {
title = 'Angular Component Example'; // Property
}
• The @Component decorator is used to provide metadata for the component.
• selector: The custom HTML tag that will represent this component in the view (<app-
root></app-root>).
• templateUrl: Path to the external HTML template.
• styleUrls: Path to the external CSS styles.
Building Template (app.component.html):
<h1>{{ title }}</h1> <!-- The title property is bound using interpolation -->
This is the HTML view for the component, which displays the title property from the
TypeScript class.
Styles (app.component.css):
h1 {
color: blue;
}
This CSS will style the heading in the template.
Using Constructors in Angular Components
In Angular, constructors are special methods used for initializing class members and
setting up dependencies for the component. The constructor is invoked when an instance of
the class is created, making it an ideal place to perform any setup required for the component.
Key Concepts
1. Initialization: Constructors can be used to initialize properties of a component.
2. Dependency Injection: Angular uses a dependency injection (DI) system that allows
you to inject services or other dependencies directly into the constructor.
3. Lifecycle Hooks: While the constructor is used for initialization, it is often best
practice to perform component logic in lifecycle hooks like ngOnInit.
21
Structure of a Constructor in an Angular Component
A typical constructor in an Angular component follows this structure:
Example: simple component that displays the date
import { Component } from '@angular/core';

@Component({
selector: 'app-date-display',
templateUrl: './date-display.component.html',
styleUrls: ['./date-display.component.css']
})
export class DateDisplayComponent {
currentDate: string;

constructor() {
// Initialize currentDate with the current date
this.currentDate = new Date().toLocaleDateString();
}
}
Using External Templates:
Using external templates in Angular components helps maintain a clean separation between the
component logic (TypeScript) and the view (HTML). This practice is especially beneficial for
larger applications where components can become complex.
Under the component decorator, place the keyword templateurl followed by the path from the
root of the application to your template HTML file. Here is an example.
@Component({
selector: 'my-app’,
templateUrl: /view.example.html
})

22
use the keyword styleurls to tell the component about external stylesheets. The
difference with the external stylesheets is that pass in an array of one or more stylesheets. The
following example shows how to import external stylesheets:
@Component ({
selector: 'my-app’,
templateUrl: /view.example.html"
styleUrls: ["./stylesl.css", "./styles2.css"]
})

23
VI. EXPRESSIONS
Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved
by AngularJS and the result is returned back to where the expression is written. The expressions in
AngularJS are written in double braces: {{ expression }}. They behave similar to ng-bind directives:
ng-bind=”expression”.
Syntax:
{{ expression }}
Example 1:
This example displays the name that we feed in the ng-init directive.
<!DOCTYPE html>
<html>
<head>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<title>AngularJS Expression</title>
</head>
<body style="text-align:center">

24
<h1 style="color:green">Good Morning</h1>
<h3>AngularJS Expressions</h3>
<div ng-app=""ng-init="name=''Hello">
<p> {{ name }} is a portal for geeks.</p>
</div>
</body>
</html>

VII. DATA BINDING


Data binding deals with how to bind your data from component to HTML DOM elements
(Templates). We can easily interact with application without worrying about how to insert your data.
We can make connections in two different ways one way and two-way binding.
One-way data binding
One-way data binding is a one-way interaction between component and its template. If you perform
any changes in your component, then it will reflect the HTML elements. It supports the following
types −

String interpolation
In general, String interpolation is the process of formatting or manipulating strings. In Angular,
Interpolation is used to display data from component to view (DOM). It is denoted by the
expression of {{ }} and also known as mustache syntax.
Let’s create a simple string property in component and bind the data to view.
export class TestComponent implements OnInit
{ appName = "My first app in Angular 8";
}
Move to test.component.html file and add the below code −
<h1>{{appName}}</h1>
Add the test component in your app.component.html file by replacing the existing content as
follows −
<app-test></app-test>

25
Finally, start your application (if not done already) using the below command − ng serve

OUTPUT :

Property binding
Property binding is used to bind the data from property of a component to DOM elements. It is
denoted by [].
Let’s understand with a simple example.
Add the below code in test.component.ts file.
export class TestComponent
{ userName:string = "Peter";
}
Add the below changes in view test.component.html,
<input type="text" [value]="userName">
Here,
userName property is bind to an attribute of a DOM element <input> tag. Finally, start your
application (if not done already) using the below command − ng serve

26
Attribute binding
Attribute binding is used to bind the data from component to HTML attributes. The syntax is as
follows −
<HTMLTag [attr.ATTR]="Component data">
For example,
<td [attr.colspan]="columnSpan"> ... </td>
Let’s understand with a simple example.
Add the below code in test.component.ts file.
export class TestComponent
{ userName:string = "Peter";
}
Add the below changes in view test.component.html,
<input type="text" [value]="userName">
Here,
userName property is bind to an attribute of a DOM element <input> tag. Finally, start your
application (if not done already) using the below command − ng serve

27
Class binding
Class binding is used to bind the data from component to HTML class property. The syntax is as
follows −
<HTMLTag [class]="component variable holding class name">

Class Binding provides additional functionality. If the component data is boolean, then the class will
bind only when it is true. Multiple class can be provided by string (“foo bar”) as well as Array of
string. Many more options are available.
For example,
<p [class]="myClasses">
Let’s understand with a simple example.
Add the below code in test.component.ts file,
export class TestComponent
{ myCSSClass = "red"; applyCSSClass = false;
}
Add the below changes in view test.component.html.
p [class]="myCSSClass">This paragraph class comes from *myClass* property </p>
<p [class.blue]="applyCSSClass">This paragraph class does not apply</p>
Add the below content in test.component.css.
.red {

28
color: red;
}
.blue {
color: blue;
}
Finally, start your application (if not done already) using the below command − ng serve The final
output will be as shown below −

Style binding
Style binding is used to bind the data from component into HTML style property. The syntax is as
follows −
<HTMLTag [style.STYLE]="component data">
For example,
<p [style.color]="myParaColor"> ... </p>
Let’s understand with a simple example.
Add the below code in test.component.ts file.
myColor = 'brown';
Add the below changes in view test.component.html.
<p [style.color]="myColor">Text color is styled using style binding</p> Finally, start your
application (if not done already) using the below command − ng serve The final output will be
as shown below −

29
Two-way data binding
Two-way data binding is a two-way interaction, data flows in both ways (from component to views
and views to component). Simple example is ngModel. If you do any changes in your property (or
model) then, it reflects in your view and vice versa. It is the combination of property and event
binding.

NgModel
NgModel is a standalone directive. ngModel directive binds form control to property and property
to form control. The syntax of ngModel is as follows −
<HTML [(ngModel)]="model.name" />
For example,
<input type="text" [(ngModel)]="model.name" />
Let’s try to use ngModel in our test application.
Configure FormsModule in AppModule (src/app/app.module.ts)
VIII. ANGULARJS DIRECTIVES :
AngularJS facilitates you to extend HTML with new attributes. These attributes are called
directives.
There is a set of built-in directive in AngularJS which offers functionality to your applications. You
can also define your own directives.
Directives are special attributes starting with ng- prefix. Following are the most common directives:

o ng-app: This directive starts an AngularJS Application.


o ng-init: This directive initializes application data.
30
o ng-model: This directive defines the model that is variable to be used in AngularJS.
o ng-repeat: This directive repeats html elements for each item in a collection.
ng-app directive
ng-app directive defines the root element. It starts an AngularJS Application and automatically
initializes or bootstraps the application when web page containing AngularJS Application is loaded.
It is also used to load various AngularJS modules in AngularJS Application.
See this example:
In following example, we've defined a default AngularJS application using ng-app attribute of a div
element.

<div ng-app = "">


...
</div>
ng-init directive
ng-init directive initializes an AngularJS Application data. It defines the initial values for an
AngularJS application.
In following example, we'll initialize an array of countries. We're using JSON syntax to define array
of countries.

<div ng-app = "" ng-init = "countries = [{locale:'en- IND',name:'India'}, {locale:'en-


PAK',name:'Pakistan'}, {locale:'en- AUS',name:'Australia'}]">
...
</div>
ng-model directive:
ng-model directive defines the model/variable to be used in AngularJS Application. In following
example, we've defined a model named "name".
<div ng-app = "">
...
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

31
ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In following example, we've
iterated over array of countries.

1. <div ng-app = "">

2. ...
3. <p>List of Countries with locale:</p>
4.
5. <ol>
6. <li ng-repeat = "country in countries">
7. {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
8. </li>
9. </ol>

AngularJS Directives List


AnglarJS directives are used to add functionality to your application. You can also add your own
directives for your applications.
Following is a list of AngularJS directives:

Directive Description

ng-change It specifies an expression to evaluate when content is being changed by the user.

ng-checked It specifies if an element is checked or not.

ng-class It specifies css classes on html elements.

ng-class-even It is same as ng-class, but will only take effect on even rows.

ng-class-odd It is same as ng-class, but will only take effect on odd rows.

ng-click It specifies an expression to evaluate when an element is being clicked.

ng-cloak It prevents flickering when your application is being loaded.

32
ng-controller It defines the controller object for an application.

33

You might also like