0% found this document useful (0 votes)
116 views50 pages

Full Stack UNIT 4

Express and angular

Uploaded by

magentaveena24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
116 views50 pages

Full Stack UNIT 4

Express and angular

Uploaded by

magentaveena24
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

UNIT 4

EXPRESS AND ANGULAR

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

Logo :

Express.js, or simply Express, is a back end web application


framework for building RESTful APIs with Node.js, released as free and
open-source software under the MIT License. It is designed for
building web applications and APIs.[3] It has been called the de facto
standard server framework for Node.js.[

Developer(s) TJ Holowaychuk, StrongLoop and others

Initial release 16 November 2010; 12 years ago

Stable release 4.18.1 (April 29, 2022; 14 months ago[1][2]) [±]

Repository Express.js Repository

Written in JavaScript

Platform Node.js

Type Web framework

License MIT License

Website expressjs.com
Features

 Robust routing
 Concentrate on high-performance
 HTTP helpers (redirection, caching, etc)

What is Express used for?


 Express is a node js web application framework that provides
broad features for building web and mobile applications.
 It is used to build a single page, multipage, and hybrid web
application.
 It's a layer built on the top of the Node js that helps manage
servers and routes.
 Express.js is a server-side application framework that wraps HTTP
requests and responses, and makes it easy to map URLs to
server-side functions.

Installing Express:
Firstly, install the Express framework globally using NPM so that it can
be used to create a web application using node terminal.

$ npm install express --save


The above command saves the installation locally in
the node_modules directory and creates a directory express inside
node_modules. You should install the following important modules along
with express −
 body-parser − This is a node.js middleware for handling JSON,
Raw, Text and URL encoded form data.
 cookie-parser − Parse Cookie header and populate req.cookies
with an object keyed by the cookie names.
 multer − This is a node.js middleware for handling multipart/form-
data.

$ npm install body-parser --save


$ npm install cookie-parser --save
$ npm install multer --save

Hello world Example


Following is a very basic Express app which starts a server and listens on
port 8081 for connection. This app responds with Hello World! for
requests to the homepage. For every other path, it will respond with a 404
Not Found.
var express = require('express');
var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
})

var server = app.listen(8081, function () {


var host = server.address().address
var port = server.address().port

console.log("Example app listening at http://%s:%s", host, port)


})

Save the above code in a file named server.js and run it with the
following command.

$ node server.js
You will see the following output −
Example app listening at http://0.0.0.0:8081
Open http://127.0.0.1:8081/ in any browser to see the following result.

Express.js Routing:
Routing is made from the word route. It is used to determine the specific
behavior of an application. It specifies how an application responds to a
client request to a particular route, URI or path and a specific HTTP
request method (GET, POST, etc.). It can handle different types of HTTP
requests.
Let's take an example to see basic routing.

Using middleware

Express is a routing and middleware web framework that has minimal


functionality of its own: An Express application is essentially a series of
middleware function calls.
Middleware functions are functions that have access to the request
object (req), the response object (res), and the next middleware
function in the application’s request-response cycle. The next
middleware function is commonly denoted by a variable named next.

Middleware functions can perform the following tasks:


 Execute any code.
 Make changes to the request and the response objects.
 End the request-response cycle.
 Call the next middleware function in the stack.

If the current middleware function does not end the request-response


cycle, it must call next() to pass control to the next middleware
function. Otherwise, the request will be left hanging.

An Express application can use the following types of middleware:

 Application-level middleware
 Router-level middleware
 Error-handling middleware
 Built-in middleware
 Third-party middleware
WHAT IS CORS MIDDLWARE ?
WHAT IS CSRF MIDDLWARE ?

Application-level middleware:
Bind application-level middleware to an instance of the app object by
using the app.use() and app.METHOD() functions, where METHOD is
the HTTP method of the request that the middleware function handles
(such as GET, PUT, or POST) in lowercase.

Router-level middleware:
Router-level middleware works in the same way as application-level
middleware, except it is bound to an instance of express.Router().
const router = express.Router()

Load router-level middleware by using


the router.use() and router.METHOD() functions.

Error-handling middleware:
Define error-handling middleware functions in the same way as
other middleware functions, except with four arguments instead
of three, specifically with the signature (err, req, res,
next)):

Built-in middleware:
Starting with version 4.x, Express no longer depends on Connect. The
middleware functions that were previously included with Express are
now in separate modules; see the list of middleware functions.

Express has the following built-in middleware functions:

 express.static serves static assets such as HTML files, images,


and so on.
 express.json parses incoming requests with JSON
payloads. NOTE: Available with Express 4.16.0+
 express.urlencoded parses incoming requests with URL-encoded
payloads. NOTE: Available with Express 4.16.0+

Third-party middleware
Use third-party middleware to add functionality to Express apps.

Install the Node.js module for the required functionality, then load it in
your app at the application level or at the router level.
The following example illustrates installing and loading the cookie-
parsing middleware function cookie-parser.

$ npm install cookie-parser

File: routing_example.js

var express = require('express');


var app = express();
app.get('/', function (req, res) {
console.log("Got a GET request for the homepage");
res.send('Welcome to JavaTpoint!');
})
app.post('/', function (req, res) {
console.log("Got a POST request for the homepage");
res.send('I am Impossible! ');
})
app.delete('/del_student', function (req, res) {
console.log("Got a DELETE request for /del_student");
res.send('I am Deleted!');
})
app.get('/enrolled_student', function (req, res) {
console.log("Got a GET request for /enrolled_student");
res.send('I am an enrolled student.');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {
console.log("Got a GET request for /ab*cd");
res.send('Pattern Matched.');
})
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port) })
You see that server is listening.

Now, you can see the result generated by server on the local host
http://127.0.0.1:8000

Output:

This is the homepage of the example app.

Note: The Command Prompt will be updated after one successful


response.

You can see the different pages by changing


routes. http://127.0.0.1:8000/enrolled_student
Updated command prompt:

This can read the pattern like abcd, abxcd, ab123cd, and so on.

Next route http://127.0.0.1:8000/abcd

Next route http://127.0.0.1:8000/ab12345cd


Updated command prompt:

ExpressJS Request & Response


Request and Response object both are the callback function parameters
and are used for Express.js and Node.js. You can get the request query,
params, body, headers, and cookies. It can overwrite any value or
anything there.
Request object

Express.js is a request & response objects parameters of the


callback function and are used for the Express applications.
The request object represents the HTTP request and contains
properties for the request query string, parameters, body, HTTP
headers, etc.

Syntax : app.get(‘/’, function (req, res) { })


Request Object Properties

req.accepts (types)

It is used to the check content types are acceptable, based on the request
accept HTTP header field.

Example :
req.accepts('html');
//=>?html?
req.accepts('text/html');
// => ?text/html?

req.get(field)

req.get is used to returns the specified HTTP request header field.


Example :
req.get('Content-Type');
// => "text/plain"
req.get('content-type');
// => "text/plain"
req.get('Something');
// => undefined

req.is(type)

If the incoming request is “CONTENT-TYPE”, this method returns true.


HTTP header field matches the MIME type by the type parameter.

Example :
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true

req.param(name [, defaultValue])

req.param method is used to fetch the value of param name when present.

Example :
// ?name=sonia
req.param('name')
// => "sonia"
// POST name=sonia
req.param('name')
// => "sonia"
// /user/soniafor /user/:name
req.param('name')
// => "sonia"
Response Object

The response object specifies the HTTP response when an Express app
gets an HTTP request. The response is sent back to the client browser and
allows you to set new cookies value that will write to the client browser.

Response Object Properties


S.No properties Description

res.app is hold a reference to the instance of the express application that


1 res.app
is using the middleware.

Specify an object that contains response local variables scoped to the


2 res.locals
request.

Response Object Method

There are various types of response object method, these methods are
represented below :

Response Append Method

Syntax : res.append(field, [value])

Response append method appends the specified value to the HTTP


response header field. That means if the specified value is not appropriate
so this method redress that.

Example :
res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Warning', '299 Miscellaneous warning');
Response Attachment Method

Syntax : res.attachment(‘path/to/js_pic.png’);

Response attachment method allows you to send a file as an attachment in


the HTTP response.

Example :
res.attachment('path/to/js_pic.png'); .

Response Cookie Method

Syntax: res.cookie(name, value [, options])

It is used to set a cookie name to value. The value can be a string or object
converted to JSON.

Example :
res.cookie('name', 'alish', { domain: '.google.com', path: '/admin',
secure: true });
res.cookie('Section', { Names: [sonica,riya,ronak] });
res.cookie('Cart', { items: [1,2,3] }, { maxAge: 900000 });

Response Download Method

Syntax: res.download(path [, filename] [, fn])

Example:
res.download('/report-12345.pdf');

res.download method is transfer file at path as an “attachment” and the


browser to prompt user for download.
Response End Method

Syntax: res.end([data] [, encoding])

Response end method is used to end the response process.

Example :
res.end();
res.status(404).end();

Response Get Method

Syntax : res.get(field)

res.get method provides HTTP response header specified by field.

Example :
res.get('Content-Type');

Response JSON Method

Syntax : res.json([body])

Response JSON method returns the response in JSON format.

Example :
res.json(null)
res.json({ name: 'alish' })

Response Render Method

Syntax : res.render(view [, locals] [, callback])


Response render method renders a view and sends the rendered HTML
string to the client.

Example :
// send the rendered view to the client

res.render('index');

// pass a local variable to the view

res.render('user', { name: 'monika' }, function(err, html) {

// ...

});

Response Status Method

Syntax : res.status(code)

res.status method sets an HTTP status for the response.

Example :
res.status(403).end();
res.status(400).send('Bad Request');

Response Type Method

Syntax : res.type(type)

res.type method sets the content-type HTTP header to the MIME type.

Example :
res.type('.html'); // => 'text/html'
res.type('html'); // => 'text/html'
res.type('json'); // => 'application/json'
res.type('application/json'); // => 'application/json'
res.type('png'); // => image/png:
Angular :

Angular (also referred to as "Angular 2+")[4] is a TypeScript-based, free


and open-source single-page web application framework led by the
Angular Team at Google and by a community of individuals and
corporations. Angular is a complete rewrite from the same team that
built AngularJS.

Initial release 2.0 / 14 September 2016;


6 years ago[1]

Stable release 16.1.6[2] / 19 July 2023;


8 days ago

Preview release 14.0.0-next.0 /


26 January 2022; 18
months ago[3]

Repository Angular Repository


Written in TypeScript, JavaScript

Platform Web platform

Type Web framework

License MIT License

Why Angular?

JavaScript is the most commonly used client-side scripting language. It


is written into HTML documents to enable interactions with web pages in
many unique ways. As a relatively easy-to-learn language with pervasive
support, it is well-suited to develop modern applications.

But is JavaScript ideal for developing single-page applications that


require modularity, testability, and developer productivity? Perhaps not.

These days, we have a variety of frameworks and libraries designed to


provide alternative solutions. With respect to front-end web
development, Angular addresses many, if not all, of the issues
developers face when using JavaScript on its own .
Advantages of Angular :

Limitations of Angular :
TypeScript :

TypeScript lets you write JavaScript the way you really want to. TypeScript is a
typed superset of JavaScript that compiles to plain JavaScript. TypeScript is
pure object oriented with classes, interfaces and statically typed like C# or Java.
The popular JavaScript framework Angular 2.0 is written in TypeScript.
Mastering TypeScript can help programmers to write object-oriented programs
and have them compiled to JavaScript, both on server side and client side.

Why should I use TypeScript ?

JavaScript is a loosely typed language. It can be difficult to understand what


types of data are being passed around in JavaScript.

In JavaScript, function parameters and variables don't have any information!


So developers need to look at documentation, or guess based on the
implementation.

TypeScript allows specifying the types of data being passed around within the
code, and has the ability to report errors when the types don't match.

For example, TypeScript will report an error when passing a string into a
function that expects a number. JavaScript will not.
Paradigm Multi-
paradigm: functional, generic, imperative, object-
oriented

Designed by Microsoft

Developer Microsoft

First appeared 1 October 2012; 10 years ago[1]

Stable release 5.1.6[2] / 5 July 2023; 16 days ago

Filename .ts, .tsx, .mts, .cts


extensions

TypeScript and ECMAScript :


The ECMAScript specification is a standardized specification of a scripting
language. There are six editions of ECMA-262 published. Version 6 of the
standard is codenamed "Harmony". TypeScript is aligned with the
ECMAScript6 specification.

TypeScript adopts its basic language features from the ECMAScript5


specification, i.e., the official specification for JavaScript. TypeScript
language features like Modules and class- based orientation are in
line with the EcmaScript 6 specification. Additionally, TypeScript also
embraces features like generics and type annotations that aren’t a part of
the EcmaScript6 specification.

TypeScript is a language extension that adds features to ECMAScript . It gives


Additional features that include :

 Type annotations and compile-time type checking


 Type inference
 Type erasure
 Interfaces
 Enumerated types
 Generics
 Namespaces
 Async/await

Components of TypeScript :

 Language
 The TypeScript Compiler
 The TypeScript Language Service

The benefits of TypeScript include :


 Compilation
 Strong Static Typing
 TypeScript supports type definitions for existing JavaScript libraries.

 TypeScript supports Object Oriented Programming concepts like classes,


interfaces, inheritance, etc.
Features of TypeScript:
 TypeScript is just JavaScript
 TypeScript supports other JS libraries
 JavaScript is TypeScript
 TypeScript is portable

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.

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.

Angular components are reusable and can be layered inside


other components, allowing developers to create sophisticated
user interfaces by mixing smaller, simpler components.
Components can connect with one another via inputs, outputs,
and services, making it easier to handle complicated
interactions between different portions of the program.

What Are Angular Components?

Components are the building blocks of a UI in an Angular application.


These components are associated with a template and are a subset of
directives.

The above image gives the tree structure of classification. There’s a root
component, which is the AppComponent, that then branches out into
other components creating a hierarchy.
Here are some of the features of Angular Component:

 Components are typically custom HTML elements, and each of


these elements can instantiate only one component.

 A TypeScript class is used to create a component. This class is


then decorated with the “@Component” decorator.

 The decorator accepts a metadata object that gives information


about the component.

 A component must belong to the NgModule in order for it to be


usable by another component or application.

 Components control their runtime behavior by implementing


Life-Cycle hooks.

The above image shows an App component, which is a pure TypeScript class
decorated with the “@Component” decorator. The metadata object provides
properties like selector, templateUrl, and so on—the templateUrL points to an
HTML file that defines what you see on your application.

In the index.html file, <app-root> tag corresponds to component’s selector. By


doing so, Angular will inject the corresponding template of the component.
A component definition has three major parts: component class, template,
and meta data.
1. Component Class :
Each component defines a component class which is essentially a
TypeScript class. A component class contains the data and logic related to
the component, where data is used in properties and logic are used in
methods. These enclosed data and logic are linked to an HTML template
that defines a view that is rendered at the target section of the application’s
view.

The class immediately below the @Component decorator is the component


class.

export class HelloComponent {

title: “Hello Component”

message: string = “Hello World”

constructor() { }

printMessage() = {

console.log(this.message)

}
}

In the above AppComponent class, message is the property (data) and


printMessage is the method (logic). The constructor function is a TS class
constructor.

Component properties and methods can bind with the view (HTML template)
using Data Binding.

2. Template :
The template defines the view of the component. It is a combination of
regular HTML and Angular template syntax that alters the regular HTML
based on the state and logic of the application and DOM data.

Views are organized hierarchically. Angular allows to modification or display


and hiding entire UI sections or pages as a unit. The Component can have
only one template, and the host view of a component is defined by the
template that is immediately associated with it. Additionally, the component
can define a view hierarchy that has embedded views hosted by other
components.

Template use data binding to connect the application with the


corresponding DOM data, pipes for data transformation before the actual
rendering of the component to the view, and directives for the application
logic that controls the view of the component.

<h2>{ { title } }</h2>

<button type="button" (click)="printMessage()">

Print message

</button>
3. Metadata :
Metadata Provides additional information about the component to Angular.
Angular uses this information to process the class. The class immediately below
the @Component decorator is the component class. The component decorator
specifies the metadata for the component class of the Angular component.

A component’s metadata stores the information to obtain the major building blocks
required to create and present the component and its view. Angular reads the
metadata and connects the corresponding HTML template with the component
and configures how the component can be referenced in HTML and what services
it requires.

Important Component metadata configuration options:

CONFIGURATION
DETAILS
OPTIONS

The selector property is a CSS selector that tells Angular to


create and insert an instance of this component wherever a
selector
corresponding component tag is found in any template
HTML

The HTML template that defines our host view. We can


pass inline template (using a template property) or an
template/
external template (using a templateUrl property). A
templateUrl
Component can have only one template, either use inline
template or external template, but not both.

An array of Angular component providers to import


providers
injectable dependencies for the services that are used in
the component. Service is a broad category encompassing
any value, function, or feature required in the component,
albeit doesn’t affect the view directly.

Adds CSS styles to the component as inline styles (using


styles/ styleUrls style property). The styles used here are specific to the
component’s host view.

@Component({

selector: 'app-hello',

template: '

<h2>{ { title } }</h2>

<button type="button" (click)="printMessage()">

Print message

</button>

',

styles: [‘./hello-app.component.css’]

})

export class HelloComponent implements OnInit {

/* . . . */

AngularJS 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">

<h1 style="color:green">GeeksforGeeks</h1>

<h3>AngularJS Expressions</h3>

<div ng-app=""ng-init="name='GeeksforGeeks'">

<p> {{ name }} is a portal for geeks.</p>

</div>

</body>

</html>

OUTPUT :
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.

Add the below code in test.component.ts file as follows −


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

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 {
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 −

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)

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


imports: [
BrowserModule,
FormsModule
]
})
export class AppModule { }

Working example
Let us implement all the concept learned in this chapter in our ExpenseManager application.

Create an application
Use below command to create the new application.

cd /path/to/workspace
ng new expense-manager
Here,
new is one of the command of the ng CLI application. It will be used to create new application.
It will ask some basic question in order to create new application. It is enough to let the
application choose the default choices. Regarding routing question as mentioned below,
specify No.

Would you like to add Angular routing? No


Once the basic questions are answered, the ng CLI application create a new Angular
application under expense-manager folder.
Let us move into the our newly created application folder.

cd expense-manager
Let us start the application using below comman.
ng serve
Let us fire up a browser and opens http://localhost:4200. The browser will show the
application as shown below −

Let us change the title of the application to better reflect our application.
Open src/app/app.component.ts and change the code as specified below −

export class AppComponent {


title = 'Expense Manager';
}
Our final application will be rendered in the browser as shown below −
Add a component
Create a new component using ng generate component command as specified below −

ng generate component expense-entry


Output
The output is as follows −

CREATE src/app/expense-entry/expense-entry.component.html (28 bytes)


CREATE src/app/expense-entry/expense-entry.component.spec.ts (671 bytes)
CREATE src/app/expense-entry/expense-entry.component.ts (296 bytes)
CREATE src/app/expense-entry/expense-entry.component.css (0 bytes)
UPDATE src/app/app.module.ts (431 bytes)
Here,

 ExpenseEntryComponent is created under src/app/expense-entry folder.


 Component class, Template and stylesheet are created.
 AppModule is updated with new component.
Add title property to ExpenseEntryComponent (src/app/expense-entry/expense-
entry.component.ts) component.

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

@Component({
selector: 'app-expense-entry',
templateUrl: './expense-entry.component.html',
styleUrls: ['./expense-entry.component.css']
})
export class ExpenseEntryComponent implements OnInit {
title: string;
constructor() { }

ngOnInit() {
this.title = "Expense Entry"
}
}
Update template, src/app/expense-entry/expense-entry.component.html with below
content.

<p>{{ title }}</p>


Open
src/app/app.component.html
and include newly created component.

<h1>{{ title }}</h1>


<app-expense-entry></app-expense-entry>
Here,
app-expense-entry is the selector value and it can be used as regular HTML Tag.
The output of the application is as shown below –

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

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.

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


ng-copy It specifies a behavior on copy events.

ng-csp It changes the content security policy.

ng-cut It specifies a behavior on cut events.

ng-dblclick It specifies a behavior on double-click events.

ng-focus It specifies a behavior on focus events.

ng-hide It hides or shows html elements.

You might also like