MST Lab Manual
MST Lab Manual
Introduction to Node JS
The mean stack is a JavaScript-based framework for developing web applications. MEAN is named after
MongoDB, Express, Node and Angular, the four key technologies that make up the layers of thestack.
Node.js
Node.js is an open-source platform and provides a runtime environment for executing the javascript code. It is
mainly used for building the back-end application. Since there are two types of apps, such as web apps and
mobile apps, where web apps run on the browser and mobile apps run on mobile devices. Both web app and
mobile app are the client apps to whichthe user interacts. These apps require to communicate with the backend
services to store the data, send emails, push notifications. Node.js is an ideal platform to build highly scalable,
data-intensive, and real-time applications. It can be used for agile development and highly-scalableservices.
For example, PayPal is a java and spring-based application using Node.js.
Angular.js
Angular.js is a JavaScript framework that is used to develop web applications. This frameworkis developed by
the Google. Now, the question arises that there are many javascript frameworks available in the market.
MongoDB
MongoDB is the database used in web development. It is a NoSQL database, and a NoSQL database can be
defined as a non-relational and document-oriented database management system. As it is a document-oriented
database management system, so it stores the data in the form of documents. The SQL databases use SQL
query language to query the database, whereas the MongoDB is a NoSQL database that uses BSON language
to query the database.
Express.js
Express.js is a free and open-source software used as a back-end web application framework.It is commonly
used in the popular development stacks like MEAN with a MongoDB database.The Express.js was developed
by TJ Holowaychuk.
EXPERIMENT-2
Exploring language addition to V8 JavaScript Engine
What is a V8 Engine?
V8 is a C++-based open-source JavaScript engine developed by Google. It was originally designed
for Google Chrome and Chromium-based browsers (such as Brave) in 2008, but it was later utilized
to create Node.js for server-side coding. Inreality, JSON-based No-SQL databases like Couchbase
and the widely used MongoDB use the V8 engine. V8 also powers Electron, a prominent desktop
application framework, and Demo, the latest server-side runtime environment.
V8 is known to be a JavaScript engine because it takes JavaScript code andexecutes it while
browsing in Chrome. It provides a runtime environment for the execution of JavaScript code. The
best part is that the JavaScript engineis completely independent of the browser in which it runs. This
is the feature that led Node.js designers to choose the V8 engine to power the framework, and the
rest is history. The V8 enginewas also utilized to construct desktop frameworks and databases as
Node.JS grew in popularity.
Here the code is interpreted in a manner, where the arguments passed areonly ofinteger type. i.e the
function will only work for integer values.
Here the code is interpreted in a manner, where the arguments passed caneither be of integer type or
string. i.e the function will work for both integers as well as strings. Thereby, the running time of the
function is faster if the type of arguments received is not modified. Inline caches keep track of
howfrequently they’re used and provide necessary feedback to the Turbofan compiler. The Compiler
takes the byte code and type feedback from the interpreter and tries to optimize the code andproduces
new byte code.
Suppose the compiler compiles a function assuming the data fetched from the APIcall is of type
String, the code fails when the data received is of typeobject. In thiscase, the compiler de-compiles
the code, falls back to the interpreter, and updates the feedback.
The Compilation and Execution of the JavaScript code go hand in hand.
Below is the diagrammatic representation of the compilation of JavaScript code.
The V8 engine tries to free up the memory heap, by clearing out unusedfunctions,clearing out
timeouts, clearing out intervals, etc.
Now, let’s understand the process of Garbage Collection.
Garbage Collection: It is an important aspect of programming and the techniques used by the
garbage collector have improved the latency, page load, pause times, etc.The V8 engine is provided
with the Orinoco GarbageCollector which internally uses the Mark and Sweep Algorithm to free up
space from the memory heap.
The Orinoco Garbage Collector uses three ways to collect the trash:
Parallel: In the parallel collection, the main JavaScript thread uses the help offew helper threads
parallelly to clear out the garbage, as a result,the main execution is stopped only for a while.
Incremental: In the incremental collection, the main JavaScript thread takes turns to collect the
garbage i.e in an incremental fashion. This typeof collectionis used to further reduce the latency of
the main thread. Example: The JavaScript thread first collects the garbage for some time and then
switches to the main execution for a while and then switches back to garbage collection. This process
goes on until the entire garbageis collected.
Concurrent: In the concurrent collection, the main JavaScript thread is notdisturbed and the entire
Garbage is collected by the helper threads inthe background.
EXPERIMENT-3
UNDERSTANDING NODE.JS
MEAN Stack is one of the most popular Technology Stack. It is used to develop a Full Stack
Web Application. Although it is a Stack of different technologies, all of these are based on JavaScript
language.
MEAN Stands for:
M – MongoDB
E – Express
A – Angular
N – Node.js
This stack leads to faster development as well as the deployment of the Web Application. Angular is
Frontend Development Framework whereas Node.js, Express, and MongoDB are used for Backend
development as shown in the belowfigure
Flow of Data in MEAN Stack Application: Here, each module communicateswith the others in order
to have a flow of the data fromServer/Backend to Client/Frontend.
Getting Started with each Technology with examples: The description ofeach Technology in this
Stack as well as the links to learn them are given below:
Node.js: Node.js is used to write the Server Side Code in Javascript. Oneof themost important points
is that it runs the JavaScript code outside the Browser. It is cross-platform and Open Source.
AngularJS: Angular is a Front-end Open Source Framework developed by Google Team. This
framework is revised in such away that backward compatibility is maintained (If there is any
breaking change then Angular informs it very early). Angular projects are simple to create using
AngularCLI (Command Line Interface) tool developed by the Angular team.
Pre-requisites to learn Angular:
TypeScript
CSS Preprocessor
Template Code (Angular Material, HTML 5, etc)
Installing Angular CLI – Command Line Interface using npm (NodePackage Manager)
npm install -g @angular/cli
Now check whether it was installed correctly using below command:
ng --version
It should show something like:
Now make changes in app.component.html file and save the file, the application will reload
automatically and corresponding changes will be reflected.
MongoDB: MongoDB is a NoSQL Database. It has JSON like documents. It is document oriented
database.
Pre-requisites to learn MongoDB:
What is Database
Disadvantages of SQL Database
Creating a database:
use database_name;
Create a collection:
db.createCollection("first_collection");
Insert a record in the Collection:
db.first_collection.insertOne(
{name:"Geeks For Geeks"}
);
Print all the records in a collection:
db.first_collection.find()
ExpressJS: Express is a web Framework build on Node.js and used tomakeAPI and to build Web
Applications.
Pre-requisites to learn Express:
JavaScript/ TypeScript
Node.js
Initialize a Project by typing the following command on terminal:
npm init
It will ask some questions, Press enter in order to set all the defaultoptions. This will create
package.json file as shown below:
{
"name": "gfg-express",
"version": "1.0.0",
"description": "Basic Express Node.js Application","main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
}
Now, the package.json file will be changed to add thedependencies as shown below:
{
"name": "gfg-express",
"version": "1.0.0",
"description": "Basic Express Node.js Application","main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC","dependencies": {
"express": "^4.17.1"
}
}
Node.js has a built-in module called HTTP, which allows Node.js to transferdata over the Hyper Text
Transfer Protocol (HTTP).
The HTTP module can create an HTTP server that listens to server ports andgives a response back to
the client.
Example
var http = require('http');
The function passed into the http.createServer() method, will be executedwhen someone tries to access
the computer on port 8080.
Save the code above in a file called "demo_http.js", and initiate the file:
Initiate demo_http.js:
Example
var http = require('http'); http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello World!');res.end();
}).listen(8080);
output
The first argument of the res.writeHead() method is the status code, 200means that all is OK, the
second argument is an object containing the response headers.
This object has a property called "url" which holds the part of the url thatcomes after the domain name:
demo_http_url.js
Save the code above in a file called "demo_http_url.js" and initiate the file:
Initiate demo_http_url.js:
http://localhost:8080/summer
/summer
output
http://localhost:8080/winter
/winter
output
Split the Query String
There are built-in modules to easily split the query string into readable parts,such as the URL module.
Example
Save the code above in a file called "demo_querystring.js" and initiate thefile:
Initiate demo_querystring.js:
2017 July
output
var fs = require('fs');
Read files
Create files
Update files
Delete files
Rename files
Read Files
The fs.readFile() method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder asNode.js):
demofile1.html
<html>
<body>
<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
Example
var http = require('http');var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});res.write(data);
return res.end();
});
}).listen(8080);
output
Save the code above in a file called "demo_readfile.js", and initiate the file:
Initiate demo_readfile.js:
Create Files
The File System module has methods for creating new files:
fs.appendFile()
fs.open()
fs.writeFile()
The fs.appendFile() method appends specified content to a file. If the file doesnot exist, the file will be
created:
Example
Create a new file using the appendFile() method:
var fs = require('fs');
The fs.open() method takes a "flag" as the second argument, if the flag is "w"for "writing", the
specified file is opened for writing. If the file does not exist,an empty file is created:
Example
Create a new, empty file using the open() method:
var fs = require('fs');
fs.open('mynewfile2.txt', 'w', function (err, file) {if (err) throw err;
console.log('Saved!');
});
The fs.writeFile() method replaces the specified file and content if it exists. Ifthe file does not exist, a
new file, containing the specified content, will be created:
Example
Create a new file using the writeFile() method:
var fs = require('fs');
Update Files
The File System module has methods for updating files:
fs.appendFile()
fs.writeFile()
The fs.appendFile() method appends the specified content at the end of thespecified file:
Example
Append "This is my text." to the end of the file "mynewfile1.txt":
var fs = require('fs');
fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {if (err) throw err;
console.log('Updated!');
});
output
var fs = require('fs');
fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {if (err) throw err;
console.log('Replaced!');
});
Delete Files
To delete a file with the File System module, use the fs.unlink() method.The fs.unlink() method deletes
the specified file:
var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) {
if (err) throw err; console.log('File deleted!');
});
output
Example
Delete "mynewfile2.txt":
Rename Files
To rename a file with the File System module, use the fs.rename() method.The fs.rename() method
renames the specified file:
Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":
var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {if (err) throw err;
console.log('File Renamed!');
});
output:
EXPERIMENT-5
Buffers and streams in Node.js
Buffer in Nodejs
In Nodejs we can manipulate these memory spaces with the modulecalled Buffer built into its core.
Buffers are widely used when working with binary data at the network level. Let us remember that
many of the Nodejs modules and functionalities work implicitly based on events and manipulation of
Buffer / Streams, such as the core File System or HTTP modules that store the temporary dataflow in
a Buffer.
The code snippet above creates a Buffer containing the UTF-8 encoded bytes for the string “hello”,
this prints the following outputto the console:
const { Buffer } =
require('buffer');const buf6 =
Buffer.from('hello');
console.log(buf6);
Once the information is saved, we can perfectly read the storedcontent, here is an example:
Most of the programming languages have incorporated in their corea set of functionalities and classes
that allow you to work with Buffers and Streams in a simple way.
Stream in Nodejs
Nodejs has a module called stream that helps us with the manipulation of these flows, but depending
on the case we will usesome type of stream.
Transform: Streams that can modify or transform data asit is written and read.
If we have already worked with Nodejs before, surely we have noticed that, for example, any HTTP
server based on Nodejs, workswith reading Streams in the request to the server (Readable) and the
response to the client works with writing Streams (Writable). Thisand other core modules work in the
same way.
readableStream.push('Hello');
readableStream.push(' ');
readableStream.push('World');
readableStream.push(null);
getContentReadStream(readableStream);
Emphasizing that when creating an object of type stream, a supportbuffer for manipulation is
automatically created. The size of the chunk or buffer can be previously configured.
Events in Node.js
Every action on a computer is an event. Like when a connection is made or afile is opened.Objects in
Node.js can fire events, like the readStream object fires events when opening and closing a file:
Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');rs.on('open', function () {
console.log('The file is open');
});
Events Module
Node.js has a built-in module, called "Events", where you can create-, fire-,and listen for- your own
events.
To include the built-in Events module use the require() method. In addition,all event properties and
methods are an instance of an EventEmitter object.
In the example below we have created a function that will be executed whena "scream" event is fired.
Example
var events = require('events');
var eventEmitter = new events.EventEmitter();
//Create an event handler:
var myEventHandler = function () {console.log('I hear a scream!');
}
//Assign the event handler to an event: eventEmitter.on('scream', myEventHandler);
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 modulesalong
with express −
body-parser − This is a node.js middleware for handling JSON, Raw, Text andURL encoded form data.
cookie-parser − Parse Cookie header and populate req.cookies with an objectkeyed 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.
Request Object − The request object represents the HTTP request and has properties for the request
query string, parameters, body, HTTP headers, and soon.
Response Object − The response object represents the HTTP response that an Express app sends when
it gets an HTTP request.
You can print req and res objects which provide a lot of information related to HTTP requestand
response including cookies, sessions, URL, etc.
Basic Routing
We have seen a basic application which serves HTTP request for the homepage. Routing refersto
determining how an application responds to a client request to a particular endpoint, which is a URI
(or path) and a specific HTTP request method (GET, POST, and so on).
We will extend our Hello World program to handle more types of HTTP requests.
var express = require('express');
var app = express();
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
Now you can try different requests at http://127.0.0.1:8081 to see the output generated byserver.js.
Following are a few screens shots showing different responses for different URLs.
Screen showing again http://127.0.0.1:8081/list_user
Screen showing again http://127.0.0.1:8081/abcd
Let's modify "Hello Word" app to add the functionality to handle static files.
var express = require('express');
var app = express();
app.use(express.static('public'));
})
Save the above code in a file named server.js and run it with the following command.
$ node server.js
Now open http://127.0.0.1:8081/images/logo.png in any browser and see observe followingresult.
GET Method
Here is a simple example which passes two values using HTML FORM GET method. We aregoing to
use process_get router inside server.js to handle this input.
<html>
<body>
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as wellas the
input sent by the HTML form.
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );
})
First
Name:
Last
Name:
Now you can enter the First and Last Name and then click submit button to see the result andit should
return the following result −
{"first_name":"John","last_name":"Paul"}
POST Method
Here is a simple example which passes two values using HTML FORM POST method. We aregoing to
use process_get router inside server.js to handle this input.
<html>
<body>
</body>
</html>
Let's save the above code in index.htm and modify server.js to handle home page requests aswell as
the input sent by the HTML form.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( dirname + "/" + "index.htm" );
})
Now you can enter the First and Last Name and then click the submit buttonto see the followingresult −
{"first_name":"John","last_name":"Paul"}
File Upload
<html>
<head>
<title>File Uploading Form</title>
The following HTML code creates a file uploader form. This form has method attribute setto POST
and enctype attribute is set to multipart/form-
data
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
</body>
</html>
Let's save above code in index.htm and modify server.js to handle home page requests as wellas file
upload.
var express = require('express');
var app = express();
var fs = require("fs");
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
NOTE: This is just dummy form and would not work, but it must work at your server.
Cookies Management
You can send cookies to a Node.js server which can handle the same using the following
middleware option. Following is a simple example to print all the cookies sent by the client.
module.exports={ createCrud:function(){
data="Form data was inserted";return data;
},
fetchCrud:function(){ data="data
was fetched";return data;
},
editCrud:function(editData){
data= "Data is edited by id: "+editData;
return data;
},
UpdateCrud:function(updateId){
data= "Data was updated by id: "+updateId;
return data;
},
deleteCrud:function(deleteId){
data= "Data was deleted by id: "+deleteId;
return data;
}
}
Include model file crud-model.js in the controller file crud-controller.jsof controllers using the following
script.
var crudModel=require('../models/crud-model');
Express – View
View- In this folder, you can write HTML code for displaying a web page on the web browser. Even you
can send the data from the controller to view for displaying data dynamically.
The view will be generated with the Basic Structure of Express App and It contains viewsfolder
You can create web pages in the viewsfolder through thefollowing steps
create a file crud-operation.ejsinthe viewsfolder.
write the HTML code as the followingscript. Even you can create another
<!DOCTYPE html>
<html>
<head>
<title>CRUD Operation</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<style> table, td,
th {
border: 1px solid #ddd;text-
align: left;}
table {
border-collapse: collapse;width:
50%;}
.table-data{ position:
relative;left:150px;
top:100px;}
th, td { padding:
15px;}
</style>
</head>
<body>
<% if(typeof editData!='undefined'){ %>
<h1><%= editData %></h1>
<form method="POST" action="/crud/edit/<%=editId %>">
<input type="submit" value="Update Data">
</form>
You can load a view file crud- operation.ejsin the controllerfile crud-controller.js of the
controllers’ folder using the following
script.
res.render('crud-operation');
Route – In the route folder, you can create a custom route/link to executethe dynamic web pages.
The Route will be generated with theBasic Structure of Express App and Itcontains routesfolder
There’s a bunch of GUIs (Graphical User Interface) to work with MongoDB server such as MongoDB
Compass, Studio 3Tand so on.
They provide a graphical interface so you can easily work withyour database and perform queries instead
of using a shell andtyping queries manually.
Now it’s time for us to dive into MongoDB commands that’llhelp you to use with your future projects.
Open up your command prompt and type mongod to start theMongoDB server.
Open up another shell and type mongo to connect toMongoDB database server.
Finding the current database you’re in
Db
This command will show the current database you are in. test isthe initial database that comes by default.
Listing databases
show databases
I currently have four databases. They are: CrudDB, admin, config and local.
Go to a particular database
use <your_db_name>
Here I’ve moved to the local database. You can check this if youtry the command db to print out the
current database name.
Creating a Database
With RDBMS (Relational Database Management Systems) wehave Databases, Tables, Rows and
Columns.
But in NoSQL databases, such as MongoDB, data is stored inBSON format (a binary version of JSON).
They are stored instructures called “collections”.
In SQL databases, these are similar to Tables.
Alright, let’s talk about how we create a database in the mongoshell.
use <your_db_name>
Wait, we had this command before! Why am I using it again?!
In MongoDB server, if your database is present already, usingthat command will navigate into your
database.
But if the database is not present already, then MongoDB serveris going to create the database for you.
Then, it will navigate into it.
{
"name": "john doe","age": 25,
"location": "colombo"
}
])
The insert() method is similar to the insertMany() method. Also, notice we have inserted a new property
called location onthe document for John Doe. So if you use find, then you’ll see only for john doe the
location property is attached.
This can be an advantage when it comes to NoSQL databasessuch as MongoDB. It allows for scalability.
result
Wait...In these examples did you just notice something like _id?How did that get there?
Well, whenever you insert a document, MongoDB automaticallyadds an _id field which uniquely
identifies each document. If you do not want it to display, just simply run the following command
db.myCollection.find({}, _id: 0).pretty()Next, we’ll look at filtering data.
If you want to display some specific document, you could specify a single detail of the document which
you want to bedisplayed.
db.myCollection.find(
{
name: "john"
}
)
result
Let’s say you want only to display people whose age is less than
25. You can use $lt to filter for this.db.myCollection.find(
{
age : {$lt : 25}
}
)
Similarly, $gt stands for greater than, $lte is “less than or equalto”, $gte is “greater than or equal to” and
$ne is “not equal”.
Updating documents
Let’s say you want to update someone’s address or age, how youcould do it? Well, see the next example:
db.myCollection.update({age : 20}, {$set: {age: 23}})
The first argument is the field of which document you want to update. Here, I specify age for the
simplicity. In production environment, you could use something like the _id field.
It is always better to use something like _id to update a uniquerow. This is because multiple fields can
have
same age and name. Therefore, if you update a single row, itwill affect all rows which have same name
and age.
result
If you update a document this way with a new property, let’s say location for example, the document will
be updated with thenew attribute. And if you do a find, then the result will be:
result
If you need to remove a property from a single document, you could do something like this (let’s say you
want age to be gone):db.myCollection.update({name: "navindu"}, {$unset: age});
Removing a document
As I have mentioned earlier, when you update or delete adocument, you just need specify the _id not
just name, age, location. db.myCollection.remove({name: "navindu"});
Removing a collection
db.myCollection.remove({});
Note, this is not equal to the drop() method. The difference
is drop() is used to remove all the documents inside a collection,but the remove() method is used to delete
all the documents along with the collection itself.
Logical Operators
MongoDB provides logical operators. The picture belowsummarizes the different types of logical
operators.
EXPERIMENT-9
GETTING START WITH ANGULAR:
What is AngularJS?
AngularJS is a client side JavaScript MVC framework to develop a dynamic web application. AngularJS
was originally started as a project in Google but now, it is open source framework.
AngularJS is entirely based on HTML and JavaScript, so there is no need to learn another syntax or
language.
AngularJS is also called just "Angular".
AngularJS changes static HTML to dynamic HTML. It extends the ability of HTMLby adding built-in
attributes and components and also provides an ability to create custom attributes using simple
JavaScript.
AngularJS Example:
<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
Enter Your Name: <input type="text" ng-model="name" /> <br />Hello <label ng-bind="name"></label>
</body>
</html>
AngularJS is an open source JavaScript MVC framework for web application or web sites. It extends
the HTML and makes it dynamic. AngularJS can be used tocreate Single Page Applications.
Prerequisites
A component is basically a directive that uses a simpler configuration and that is suitable for a
component-based architecture, which is what Angular 2 is all about. Think of a component as a widget: A
piece of HTML code that you can reuse in several different places in your webapplication.
Reduce duplication: Traditionally, if the same UI component had to be present in two differentplaceson a
page (let alone two different pages in the application), the HTML code had to be duplicated. This leads to
not only an increase in code duplication but also a decrease in
maintainability, making it painful to keep the UI consistent. Components serve as a simplesolution to this
problem.
HTML bundled with logic: Under the MVC architecture, having separate files for HTML tagsand the
controller logic may seem organized but has a downside — there is no clear way of showing which
HTML content is changed or generated which part of the controller logic.
Bundling both these into a single component makes it cleaner to understand their relationshipwhile also
ensuring that one does not get changed without considering the other part.
Consistent UI: Components also offer great help in making sure the design across the application is
consistent. By enabling reusable HTML code, this practice forces you to keep yourelements uniform
wherever they are used.
Create a component
Let’s build a simple “Hello World ” component to illustrate how easy it is. The end goal for our
component will be to display this simple piece of HTML:
<span>Hello World!</span>
The syntax to create a component is fairly easy. All you have to do is declare its name and passa config
object that specifies what your component should do. In our case, it will render some basic HTML:
angular.module("myApp", [])
.component("helloWorld",{
template: 'Hello World!'
});
In order to then use that component in our code, all we need is this:
<div ng-app="myApp">
<hello-world> </hello-world>
</div>
TEMPLATES:
Templates in AngularJS are simply HTML files filled or enriched with AngularJS stuff like
attributes and directives. A directive is a marker element that is used to target a particular
attribute or class to render its behavior according to the needs. Model and controller in Angular are
combined with the templates to manipulate the view the user sees in his/her browser. Angular
templates can also accommodate CSS, Form controls, Filters, and Expressions. There are two types
of templates:
Static Template
Dynamic Templates
Interpolation:
In AngularJS, Interpolation is a way to transfer the data from a TypeScript code to an HTML template
(view), i.e. it is a method by which we can put an expression in between some text and get the value
of that expression. Interpolation basically binds the text with the expressi on value. Interpolation is a one-
way data binding. Through this, we can bind some data values from our logic. To use the interpolation
we need to put our expression into the double curly braces {{ }}. With Interpolation, only string data/
expression will be evaluated, ie., only string parameter will be used in the interpolation.
DIRECTIVES:
Directives are markers on the DOM element which tell AngularJS to attach a specified behavior to that
DOM element or even transform the DOM element with its children. Simple AngularJS allows extending
HTML with new attributes called Directives. AngularJS has a setof built-in directives whichoffers
functionality to the applications. It also defines its own directives. A directive can be defined using some
functions which are: Element name, Attribute, Class, and Comment.