0% found this document useful (0 votes)
59 views96 pages

Advanced Web Designing

Uploaded by

beyou5360
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)
59 views96 pages

Advanced Web Designing

Uploaded by

beyou5360
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

ADVANCED WEB DESIGNING

SUCHIKA PATEL
SDJ INTERNATIONAL COLLEGE, PALSANA
Unit-1 Concepts of NoSQL: MongoDB

1.1 Concepts of NoSQL. Advantages and features.

• NoSQL Database is used to refer a non-SQL or non-relational database.


• It provides a mechanism for storage and retrieval of data other than tabular
relations model used in relational databases. NoSQL database doesn't use tables
for storing data. It is generally used to store big data and real-time web
applications.

History behind the creation of NoSQL Databases

• In the early 1970, Flat File Systems are used. Data were stored in flat files and the
biggest problems with flat files are each company implement their own flat files
and there are no standards. It is very difficult to store data in the files, retrieve
data from files because there is no standard way to store data.
• Then the relational database was created by E.F. Codd and these databases
answered the question of having no standard way to store data. But later
relational database also gets a problem that it could not handle big data, due to
this problem there was a need of database which can handle every types of
problems then NoSQL database was developed.

Advantages of NoSQL

o It supports query language.


o It provides fast performance.
o It provides horizontal scalability.

MongoDB

• In recent days, MongoDB is a new and popularly used database. It is a document


based, non-relational database provider.
• Although it is 100 times faster than the traditional database but it is early to say that
it will broadly replace the traditional RDBMS. But it may be very useful in term to gain
performance and scalability.
• A Relational database has a typical schema design that shows number of tables and
the relationship between these tables, while in MongoDB there is no concept of
relationship.

MongoDB Advantages

• MongoDB is schema less. It is a document database in which one collection holds


different documents.
• There may be difference between number of fields, content and size of the
document from one to other.
• Structure of a single object is clear in MongoDB.
Unit-1 Concepts of NoSQL: MongoDB

o There are no complex joins in MongoDB.


o MongoDB provides the facility of deep query because it supports a powerful dynamic
query on documents.
o It is very easy to scale.
o It uses internal memory for storing working sets and this is the reason of its fast
access.

Distinctive features of MongoDB

o Easy to use
o Light Weight
o Extremely faster than RDBMS

Where MongoDB should be used

o Big and complex data


o Mobile and social infrastructure
o Content management and delivery
o User data management
o Data hub

Performance analysis of MongoDB and RDBMS

o In relational database (RDBMS) tables are using as storing elements, while in


MongoDB collection is used.
o In the RDBMS, we have multiple schema and in each schema we create tables to store
data while, MongoDB is a document oriented database in which data is written in
BSON format which is a JSON like format.
o MongoDB is almost 100 times faster than traditional database systems.

1.1.1 MongoDB Datatypes (String, Integer, Boolean, Double, Arrays, Objects)


Unit-1 Concepts of NoSQL: MongoDB

Data Description
Types

String String is the most commonly used datatype. It is used to store data. A string
must be UTF 8 valid in mongodb.

Integer Integer is used to store the numeric value. It can be 32 bit or 64 bit
depending on the server you are using.

Boolean This datatype is used to store boolean values. It just shows YES/NO values.

Double Double datatype stores floating point values.

Min/Max This datatype compare a value against the lowest and highest bson
Keys elements.

Arrays This datatype is used to store a list or multiple values into a single key.

Object Object datatype is used for embedded documents.

Null It is used to store null values.

Symbol It is generally used for languages that use a specific type.

Date This datatype stores the current date or time in unix time format. It makes
you possible to specify your own date time by creating object of date and
pass the value of date, month, year into it.

1.1.2 Database creation and dropping database

Create a Database

1. Click the Create Database button.

From the Databases tab, click the Create Database button to bring up the Create Database
dialog.

2. Enter database and first collection information.

• In the dialog, enter the name of the database to create and its first collection. Both
the database name and the collection name are required.
• If you want to create a capped collection, select the Capped Collection checkbox and
enter the maximum bytes.
• If you want to use custom collation on the newly created collection, select the Use
Custom Collation checkbox and select the desired collation settings.
Unit-1 Concepts of NoSQL: MongoDB

3. Click Create Database to create the database and its first collection.

Drop a Database

1. Click the trash can icon for the database.

From the Databases tab, to delete a database, click on the trash can icon for that database. A
confirmation dialog appears.

2. Confirm the database to delete.

In the dialog, enter the name of the database to delete.

3. Click Drop Database to delete the database.

1.2 create and Drop collections

• A collection is a grouping of MongoDB documents.


• Documents within a collection can have different fields.
• A collection is the equivalent of a table in a relational database system.
• A collection exists within a single database

Collections Screen
• The Collections screen lists the existing collections and views in the selected
database.
• Each list item includes the name and other general information for the collection or
view.
• To access the Collections screen for a database, from the Databases screen either:
✓ Click a Database Name in the main Databases view, or
✓ Click a database in the left navigation.
Unit-1 Concepts of NoSQL: MongoDB

Collection Information

The Collections screen displays the following information for each collection in the selected
database:
• Collection name
• Number of documents in the collection
• Average size of documents in the collection
• Total size of all documents in the collection
• Number of indexes on the collection
• Total size of all indexes on the collection
• Collation properties for the collection. Hover over a Collation banner to view the
properties for that collection.

Create a Collection
You can create new collections in an existing database.

1. Click the Create Collection button.


From the Collections screen, click the Create Collection button.

2. Enter the collection information.


In the Create Collection dialog, enter the name of the collection to create.

✓ If you want to create a capped collection, select the Capped Collection checkbox and
enter the maximum bytes.
✓ If you want to use custom collation on the collection, select the Use Custom
Collation checkbox and select the desired collation settings.

3. Click Create Collection to create the collection.

Drop a Collection
1. Click the trash can icon to delete a collection.
From the Collections screen, click on the trash can for the collection to delete. A
confirmation dialog appears.

2. Confirm the collection to delete.


In the dialog, enter the name of the collection to delete.

3. Click Drop Collection to drop the collection.

Show all the database

show dbs

Create new or switch database


Unit-1 Concepts of NoSQL: MongoDB

use databasename

To show current database

db

To delete database

Db.dropDatabase() // To delete current database

To view all collections

Show collections

To create collections

db.createCollection(‘collectionName’)

To delete collections

db.<collectionname>.drop()

1.3 CRUD operations (Insert, update, delete, find, Query and Projection

operators)

Insert

The create or insert operations are used to insert or add new documents in the collection. If
a collection does not exist, then it will create a new collection in the database. You can
perform, create operations using the following methods provided by the MongoDB:

Method Description

db.collection.insertOne() It is used to insert a single document in the collection.

db.collection.insertMany() It is used to insert multiple documents in the collection.

Example: 1
Unit-1 Concepts of NoSQL: MongoDB

In this example, we are inserting details of a single student in the form of document in the
student collection using db.collection.insertOne() method.

Example 2:
In this example, we are inserting details of the multiple students in the form of documents
in the student collection using db.collection.insertMany() method.
Unit-1 Concepts of NoSQL: MongoDB

Update

The update operations are used to update or modify the existing document in the collection.
You can perform update operations using the following methods provided by the MongoDB:
Method Description

It is used to update a single document in the collection


db.collection.updateOne() that satisfy the given criteria.

It is used to update multiple documents in the collection


db.collection.updateMany() that satisfy the given criteria.

It is used to replace single document in the collection that


db.collection.replaceOne() satisfy the given criteria.
Unit-1 Concepts of NoSQL: MongoDB

Example 1:
In this example, we are updating the age of Sumit in the student collection
using db.collection.updateOne() method. method.

Example 2:
In this example, we are updating the year of course in all the documents in the student
collection using db.collection.updateMany() method.
Unit-1 Concepts of NoSQL: MongoDB

Delete

The delete operation are used to delete or remove the documents from a collection. You
can perform delete operations using the following methods provided by the MongoDB:
Method Description

It is used to delete a single document from the collection


db.collection.deleteOne() that satisfy the given criteria.

It is used to delete multiple documents from the collection


db.collection.deleteMany() that satisfy the given criteria.
Unit-1 Concepts of NoSQL: MongoDB

Example 1:
In this example, we are deleting a document from the student collection
using db.collection.deleteOne() method.

Find

The Read operations are used to retrieve documents from the collection, or in other words,
read operations are used to query a collection for a document. You can perform read
operation using the following method provided by the MongoDB:
Unit-1 Concepts of NoSQL: MongoDB

Method Description

db.collection.find() It is used to retrieve documents from the collection.

Example 1:

In this example, we are retrieving the details of students from the student collection
using db.collection.find() method.

Query and Projection

Parameter Type Description

query document Optional. Specifies selection filter using query operators. To return
all documents in a collection, omit this parameter or pass an empty
document ({}).

projection document Optional. Specifies the fields to return in the documents that match
the query filter. To return all fields in the matching documents, omit
this parameter.
Unit-1 Concepts of NoSQL: MongoDB

1.3 Operators (Projection, update, limit (), sort ()) and Aggregation

Name Description

$eq Matches values that are equal to a specified value.

$gt Matches values that are greater than a specified value.

$gte Matches values that are greater than or equal to a specified value.

$in Matches any of the values specified in an array.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$nin Matches none of the values specified in an array.

Example

db.collection.find( { qty: { $gt: 4 } } )

Logical

Name Description

$and Joins query clauses with a logical AND returns all documents that match the conditions of
both clauses.

$not Inverts the effect of a query expression and returns documents that do not match the
query expression.

$nor Joins query clauses with a logical NOR returns all documents that fail to match both
clauses.
Unit-1 Concepts of NoSQL: MongoDB

Name Description

$or Joins query clauses with a logical OR returns all documents that match the conditions of
either clause.

Array

Name Description

$all Matches arrays that contain all elements specified in the query.

$elemMatch Selects documents if element in the array field matches all the
specified $elemMatch conditions.

$size Selects documents if the array field is a specified size.

Projection Operators

Name Description

$ Projects the first element in an array that matches the query condition.

$elemMatch Projects the first element in an array that matches the


specified $elemMatch condition.

$meta Projects the document's score assigned during $text operation.

$slice Limits the number of elements projected from an array. Supports skip
and limit slices.

limit ()
Unit-1 Concepts of NoSQL: MongoDB

• MongoDB allows you to specify the maximum number of documents to return by


making use of the limit() method which will return only the number of documents you
need.
• And as soon as you prepare a MongoDB query for the collection with the help
of db.collection.find() method, you can add on the limit() method for specifying the
limit.
• Example:

db.writers.find().pretty().limit(2)

Skip()

• It is also possible to skip some documents from a MongoDB database.


• You can perform such operations using the skip() method of MongoDB.
• In other words, it can be said that users have the power to manage or regulate where
MongoDB begins returning the query results.
• Example:

db.writers.find().pretty().skip(1)

sort ()

• For sorting your MongoDB documents, you need to make use of the sort() method.
• This method will accept a document that has a list of fields and the order for sorting.
• For indicating the sorting order, you have to set the value 1 or -1 with the specific
entity based on which the ordering will be set and displayed.
• One indicates organizing data in ascending order while -1 indicates organizing in
descending order.
• Db.test.find.sort({age:1})

Aggregation commands

• MongoDB's aggregate function will cluster out the records in the form of a collection
which can be then employed for providing operations like total number(sum), mean,
minimum and maximum, etc. from the aggregated group of data extracted.
• For performing such an aggregate function, the aggregate() method is used. The
syntax of this method looks something like this:
db.collection_name.aggregate(aggregate_operation)
Expression Description
$sum adds up the definite values of every documentUnit-1
of a Concepts
collection.
of NoSQL: MongoDB

$avg computes the average values of every document of a collection.

$min finds and returns the minimum of all values from within a collection.

$max finds and returns the maximum of all values from within a collection.

$first fetches out the first document.

$last fetches out the last document.

$addToSet feeds in the values to an array without duplication

Example:
• db.test.aggregate([
... { $group: {_id: "$age", count:{$sum:1}}}])

• db.test.aggregate( [ {$group: { _id:"age", max:{ $max:"$age"}}} ])


• db.test.aggregate( [ {$group: { _id:"age", min:{ $min:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", avg:{ $avg:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", first:{ $first:"$age"}}} ])
• db.test.aggregate( [ {$group: { _id:"age", last:{ $last:"$age"}}} ])
Unit-2: Fundamentals of React.js

2.1 Overview of React

• The world can't live without mobile and web applications in this day and age.
Everything is digitized, from booking cabs to ordering food to make bank transactions.
Thanks to the efficient frameworks that provide a seamless user experience. One such
robust frontend library is React.
2.1.1 Concepts of React.

• React is a JavaScript-based UI development library.


• Facebook and an open-source developer community run it.
• React is a library rather than a language, it is widely used in web development. The
library first appeared in May 2013 and is now one of the most commonly used
frontend libraries for web development.
• React offers various extensions for entire application architectural support, such as
Flux and React Native, beyond mere UI.

Why React?

• Easy creation of dynamic applications: React makes it easier to create dynamic web
applications because it requires less coding and offers more functionality, as opposed
to JavaScript, where coding often gets complex very quickly.

• Improved performance: React uses Virtual DOM, thereby creating web applications
faster. Virtual DOM compares the components’ previous states and updates only the
items in the Real DOM that were changed, instead of updating all of the components
again, as conventional web applications do.

• Reusable components: Components are the building blocks of any React application,
and a single app usually consists of multiple components. These components have
their logic and controls, and they can be reused throughout the application, which in
turn dramatically reduces the application’s development time.

• Unidirectional data flow: React follows a unidirectional data flow. This means that
when designing a React app, developers often nest child components within parent
components. Since the data flows in a single direction, it becomes easier to debug
errors and know where a problem occurs in an application at the moment in question.

• Small learning curve: React is easy to learn, as it mostly combines basic HTML and
JavaScript concepts with some beneficial additions. Still, as is the case with other tools
and frameworks, you have to spend some time to get a proper understanding of
React’s library.

• It can be used for the development of both web and mobile apps: We already know
that React is used for the development of web applications, but that’s not all it can do.
There is a framework called React Native, derived from React itself, that is hugely
popular and is used for creating beautiful mobile applications. So, in reality, React can
be used for making both web and mobile applications.
Unit-2: Fundamentals of React.js

• Dedicated tools for easy debugging: Facebook has released a Chrome extension that
can be used to debug React applications. This makes the process of debugging React
web applications faster and easier.

2.1.2 Using React with HTML

• React’s goal is in many ways to render HTML in web page.


• React renders HTML to the web page by using a function called
ReactDOM.render().
• Render()
The reactDOM.render() function take two arguments: HTML code and HTML
element.
• The purpose of the function is to display the specified HTML code inside the
specified HTML element.
Display a paragraph inside the root element:
ReactDOM.render(<p>Hello</p>,document.getElementById(‘root’));
Output:
<body>
<div id=”root”></div>
</body>

2.1.3 React Interactive components: Components within components and Files

• A Component is one of the core building blocks of React.


• In other words, we can say that every application you will develop in React will
be made up of pieces called components.
• Components make the task of building UIs much easier.
• You can see a UI broken down into multiple individual pieces called components
and work on them independently and merge them all in a parent component
which will be your final UI.
Unit-2: Fundamentals of React.js

Two types of components:

1. Functional Components

• Functional components are simply javascript functions.


• We can create a functional component in React by writing a javascript function.
• These functions may or may not receive data as parameters.
• In the functional Components, the return value is the JSX code to render to the DOM
tree.
• Example: Program to demonstrate the creation of functional components.
1. Filepath- src/index.js: Open your React project directory and edit
the index.js file from src folder:
import React from 'react';
import ReactDOM from 'react-dom';
import Demo from './App';

ReactDOM.render(
<React.StrictMode>
<Demo />
</React.StrictMode>,
document.getElementById('root')
);

2. Filepath- src/App.js: Open your React project directory and edit


the App.js file from src folder.
import React from 'react';
import ReactDOM from 'react-dom';

const Demo=()=>
{
Unit-2: Fundamentals of React.js

return <h1>Welcome to GeeksforGeeks</h1>;


}

export default Demo;

2. Class Components

• The class components are a little more complex than the functional components.
• The functional components are not aware of the other components in your program
whereas the class components can work with each other.
• We can pass data from one class component to other class components. We can use
JavaScript ES6 classes to create class-based components in React. Below example
shows a valid class-based component in React.

2.1.4 Passing data through Props

• Props are arguments passed into React components.


• Props are passed to components via HTML attributes.
• React Props are like function arguments in JavaScript and attributes in HTML.
• To send props into a component, use the same syntax as HTML attributes:
const myElement = <Car brand="Ford" />;
• The component receives the argument as a props object:

function Car(props) {

return <h2>I am a { props.brand }!</h2>;

Pass Data
• Props are also how you pass data from one component to another, as parameters.
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
Unit-2: Fundamentals of React.js

2.2 Class components


2.2.1 React class and class components

• When creating a React component, the component's name must start with an upper-
case letter.
• The component has to include the extends React.Component statement, this
statement creates an inheritance to React.Component, and gives your component
access to React.Component's functions.
• The component also requires a render() method, this method returns HTML.

Create a Class component called Car

import React,{Component} from ‘react’;

class Car extends React.Component {

render() {

return <h2>Hi, I am a Car!</h2>;

To use this component in your application, use similar syntax as normal HTML: <Car />

Component Constructor

• If there is a constructor() function in your component, this function will be called when
the component gets initiated.
• The constructor function is where you initiate the component's properties.
• In React, component properties should be kept in an object called state.
• The constructor function is also where you honor the inheritance of the parent
component by including the super() statement, which executes the parent
component's constructor function, and your component has access to all the functions
of the parent component (React.Component).

class Car extends React.Component {

constructor() {

super();

this.state = {color: "red"};

render() {
Unit-2: Fundamentals of React.js

return <h2>I am a Car!</h2>;

Components in Components

class Car extends React.Component {

render() {

return <h2>I am a Car!</h2>;

class Garage extends React.Component {

render() {

return (

<div>

<h1>Who lives in my Garage?</h1>

<Car />

</div>

); } }

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

2.2.2 Conditional statements, Operators, Lists


Conditional Statement

• if Statement

We can use the if JavaScript operator to decide which component to render.

Example:

import React from 'react';


import ReactDOM from 'react-dom/client';

function MissedGoal() {
return <h1>MISSED!</h1>;
Unit-2: Fundamentals of React.js

function MadeGoal() {
return <h1>GOAL!</h1>;
}

function Goal(props) {
const isGoal = props.isGoal;
if (isGoal) {
return <MadeGoal/>;
}
return <MissedGoal/>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Goal isGoal={false} />);

Operators
Logical && Operator
import React from 'react';
import ReactDOM from 'react-dom/client';

function Garage(props) {
const cars = props.cars;
return (
<>
<h1>Garage</h1>
{cars.length > 0 &&
<h2>
You have {cars.length} cars in your garage.
</h2>
}
</>
);
}

const cars = [];


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);
Ternary Operator

condition ? true : false

import React from 'react';


Unit-2: Fundamentals of React.js

import ReactDOM from 'react-dom/client';

function MissedGoal() {
return <h1>MISSED!</h1>;
}

function MadeGoal() {
return <h1>GOAL!</h1>;
}

function Goal(props) {
const isGoal = props.isGoal;
return (
<>
{ isGoal ? <MadeGoal/> : <MissedGoal/> }
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Goal isGoal={false} />);

Lists

• In React, you will render lists with some type of loop.


• The JavaScript map() array method is generally the preferred method.

function Car(props) {

return <li>I am a { props.brand }</li>;

function Garage() {

const cars = ['Ford', 'BMW', 'Audi'];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car brand={car} />)}


Unit-2: Fundamentals of React.js

</ul>

</>

);

const root =
ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

Example:

function Car(props) {

return <li>I am a { props.brand }</li>;

function Garage() {

const cars = [

{id: 1, brand: 'Ford'},

{id: 2, brand: 'BMW'},

{id: 3, brand: 'Audi'}

];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car key={car.id} brand={car.brand}


/>)}

</ul>

</>

);
Unit-2: Fundamentals of React.js

const root =
ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

2.2.3 React Events: Adding events, Passing arguments, Event objects

• Just like HTML DOM events, React can perform actions based on user events.
• React has the same events as HTML: click, change, mouseover etc.
Adding Events

<button onClick={shoot}>Take the Shot!</button>


import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = () => {
alert("Great Shot!");
}

return (
<button onClick={shoot}>Take the shot!</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

Passing Arguments
import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a) => {
alert(a);
}

return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
Unit-2: Fundamentals of React.js

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

React Event Object


import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function.
In this case, the 'click' event
*/
}

return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);
Unit-3: Forms and Hooks in React.JS

3.1 Forms: (Adding forms, Handling forms, Submitting


forms)
• Forms are an integral part of any modern web application.
• It allows the users to interact with the application as well as gather
information from the users.
• Forms can perform many tasks that depend on the nature of your
business requirements and logic such as authentication of the user,
adding user, searching, filtering, booking, ordering, etc.
• A form can contain text fields, buttons, checkbox, radio button, etc.
Creating Form
• React offers a stateful, reactive approach to build a form. The component
rather than the DOM usually handles the React form. In React, the form
is usually implemented by using controlled components.
• There are mainly two types of form input in React.
1. Uncontrolled component
• The uncontrolled input is similar to the traditional HTML form
inputs.
• The DOM itself handles the form data. Here, the HTML elements
maintain their own state that will be updated when the input
value changes.
• To write an uncontrolled component, you need to use a ref to get
form values from the DOM.
• In other words, there is no need to write an event handler for
every state update. You can use a ref to access the input field value
of the form from the DOM.

import React, { Component } from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.updateSubmit = this.updateSubmit.bind(this);
this.input = React.createRef();
}
updateSubmit(event) {
alert('You have entered the UserName and CompanyName s
uccessfully.');
Unit-3: Forms and Hooks in React.JS
event.preventDefault();
}
render() {
return (
<form onSubmit={this.updateSubmit}>
<h1>Uncontrolled Form Example</h1>
<label>Name:
<input type="text" ref={this.input} />
</label>
<label>
CompanyName:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;

2. Controlled component
• In HTML, form elements typically maintain their own state and
update it according to the user input.
• In the controlled component, the input form element is handled
by the component rather than the DOM.
• Here, the mutable state is kept in the state property and will be
updated only with setState() method.
• Controlled components have functions that govern the data
passing into them on every onChange event, rather than grabbing
the data only once, e.g., when you click a submit button. This data
is then saved to state and updated with setState() method. This
makes component have better control over the form elements
and data.
• A controlled component takes its current value through props and
notifies the changes through callbacks like an onChange event.
Unit-3: Forms and Hooks in React.JS
• A parent component "controls" these changes by handling the
callback and managing its own state and then passing the new
values as props to the controlled component. It is also called as a
"dumb component."
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('You have submitted the input successfully: ' + this.state.val
ue);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h1>Controlled Form Example</h1>
<label>
Name:
<input type="text" value={this.state.value} onChange={th
is.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default App;
Unit-3: Forms and Hooks in React.JS

SN Controlled Uncontrolled

1. It does not maintain its internal state. It maintains its internal states.

2. Here, data is controlled by the parent Here, data is controlled by the DOM itself.
component.

3. It accepts its current value as a prop. It uses a ref for their current values.

4. It allows validation control. It does not allow validation control.

5. It has better control over the form elements It has limited control over the form elements
and data. and data.

3.1.1 event.target.name and event.target.event, React


Memo
• event.target returns the DOM element that triggered an specific event,
so we can retrieve any property/ attribute that has a value.
• For example, when we console.log(e.target), we can see the class name
of the element, type, position of the mouse, etc.
• We can access the value of an event with event.target.value.
React Memo
• React Memo is a Higher Order Component (HOC) which itself wraps
around a component to memorize the rendered output and skips
unnecessary renderings.
• The component around which it’s used will generate a memorized or an
optimal version of it to speed up the render process.
• Improve the overall stability and rendering performance of your React
application.
• Allows the component to check the old props against new ones to see if
the value has changed or not.
• Useful when you expect the same result from a component:
you should wrap a component in your React app to React Memo when
you know beforehand that it will render the same result to the DOM when
given the same props to it. Thereby, it will result in a performance boost
as it will memorize the result.
• Only checks for prop changes: this means that if the props are passed
down to the component changes, then only a new render will occur. If the
props remain the same, you will always get the memorized result.
Unit-3: Forms and Hooks in React.JS
Where to use React Memo?
• Use it if you are using a pure functional component: this means that your
component is not using classes and given the same props, it always
renders the same output.
• Use it when you know beforehand that a component will render quite
often.
• Use it if the re-rendering is done using the same props given to the
component. If by any chance the props change, then it’s not a right idea
to use memorization here.
• Use it if your component is big enough to have props equality
check done by React with a decent number of UI elements.
Where NOT to use React Memo?
• Don’t use React Memo if the component isn’t heavy and renders with
different props altogether.
• Wrapping a class-based component in React Memo is undesirable and
therefore should not be used.
import React from "react";
const App = () => {
const [todo, setTodo] = React.useState([
{ title: "Shop groceries 🛒" },
{ title: "Do yoga 🧘" }
]);

const [text, setText] = React.useState("");


const handleText = (e) => { setText(e.target.value); };
const handleAddTodo = () => {
setTodo(todo.concat({ title: text }));
};
return (
<div>
<input type="text" value={text} onChange={handleText} />
<button type="button" onClick={handleAddTodo}>
<span role="img" aria-label="add emojie">

</span>
Add todo
</button>
<Todo list={todo} />
</div>
);
Unit-3: Forms and Hooks in React.JS
};

const Todo = React.memo(({ list }) => {


return (
<ul>
{list.map((item) => (
<TodoItem item={item} />
))}
</ul>
);
});
const TodoItem = React.memo(({ item }) => {
return <li>{item.title}</li>;
});
export default App;
Unit-3: Forms and Hooks in React.JS

3.1.2 Components (TextArea, Drop down list (SELECT))


TextArea
• A great advantage of using <textarea> is that it provides multi-line input
values so that all values can be completely visible to the user.
• Most of the time, <textarea> can be used to add the user’s primary and
secondary addresses so that they can be completely visible to the user.
import React, { Component } from "react";
class Textareademo extends Component {
constructor() {
super();
this.state = { textAreaValue: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ textAreaValue: event.target.value });
}
render() {
return (
<div>
<label>Enter value: </label>
<textarea
value={this.state.textAreaValue}
onChange={this.handleChange}
/>
</div>
);
}
}
export default Textareademo;
Drop down list (Select)
import * as React from 'react';
const DropDown = () => {
const options = [
{ label: 'Fruit', value: 'fruit' },
{ label: 'Vegetable', value: 'vegetable' },
{ label: 'Meat', value: 'meat' },
];
const [value, setValue] = React.useState('fruit');
Unit-3: Forms and Hooks in React.JS
const handleChange = (event) => { setValue(event.target.value);
};
return (
<div>
<Dropdown label="What do we eat?"
options={options}
value={value} onChange={handleChange}
/>
<p>We eat {value}!</p>
</div>
); };
const Dropdown = ({ label, value, options, onChange }) => {
return (
<label>
{label}
<select value={value} onChange={onChange}>
{options.map((option) => (
<option value={option.value}>{option.label}</option>
))}
</select>
</label>
); };
export default DropDown;

3.2 Hooks: Concepts and Advantages


• Hooks are the new feature introduced in the React 16.8 version.
• It allows you to use state and other React features without writing a class.
• Hooks are the functions which "hook into" React state and lifecycle
features from function components.
• It does not work inside classes.
• Hooks are backward-compatible, which means it does not contain any
breaking changes.
When to use a Hooks
If you write a function component, and then you want to add some state to
it, previously you do this by converting it to a class. But now you can do it by
using a Hook inside the existing function component.
Rules of Hooks
Unit-3: Forms and Hooks in React.JS
1. Only call Hooks at the top level
Do not call Hooks inside loops, conditions, or nested functions. Hooks should
always be used at the top level of the React functions. This rule ensures that
Hooks are called in the same order each time a component render.
2. Only call Hooks from React functions
You cannot call Hooks from regular JavaScript functions. Instead, you can call
Hooks from React function components. Hooks can also be called from custom
Hooks.
React Hooks Installation
1. $ npm install [email protected] --save
2. $ npm install [email protected] --save
Hooks State
Hook state is the new way of declaring a state in React app. Hook uses useState()
functional component for setting and retrieving state.
3.2.1 useState, useEffect, useContext
useState
• The React useState Hook allows us to track state in a function component.
• State generally refers to data or properties that need to be tracking in an
application.
• At the top of your component, import the useState Hook.
import { useState } from "react";
Initialize useState
• We initialize our state by calling useState in our function component.
• useState accepts an initial state and returns two values:
• The current state.
• A function that updates the state.
import { useState } from "react";

function FavoriteColor() {
const [color, setColor] = useState("");
}

The first value, color, is our current state.


The second value, setColor, is the function that is used to update our state.

Read State

import { useState } from "react";


import ReactDOM from "react-dom/client";

function FavoriteColor() {
Unit-3: Forms and Hooks in React.JS
const [color, setColor] = useState("red");

return <h1>My favorite color is {color}!</h1>


}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<FavoriteColor />);

Update State
import { useState } from "react";
import ReactDOM from "react-dom/client";
function FavoriteColor() {
const [color, setColor] = useState("red");

return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
onClick={() => setColor("blue")}
>Blue</button>
</>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

What Can State Hold


import { useState } from "react";
import ReactDOM from "react-dom/client";

function Car() {
const [brand, setBrand] = useState("Ford");
const [model, setModel] = useState("Mustang");
const [year, setYear] = useState("1964");
const [color, setColor] = useState("red");

return (
<>
<h1>My {brand}</h1>
<p>
It is a {color} {model} from {year}.
</p>
</>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Car />);
Unit-3: Forms and Hooks in React.JS

import { useState } from "react";


import ReactDOM from "react-dom/client";

function Car() {
const [car, setCar] = useState({
brand: "Ford",
model: "Mustang",
year: "1964",
color: "red"
});

return (
<>
<h1>My {car.brand}</h1>
<p>
It is a {car.color} {car.model} from {car.year}.
</p>
</>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Car />);

useEffect
• The useEffect Hook allows you to perform side effects in your
components.
• Some examples of side effects are: fetching data, directly updating the
DOM, and timers.
• useEffect accepts two arguments. The second argument is optional.
useEffect(<function>, <dependency>)
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Timer() {
const [count, setCount] = useState(0);

useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
Unit-3: Forms and Hooks in React.JS
return <h1>I've rendered {count} times!</h1>;
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Timer />);

• useEffect runs on every render. That means that when the count changes,
a render happens, which then triggers another effect.
• We should always include the second parameter which accepts an array.
We can optionally pass dependencies to useEffect in this array.

No dependency passed
useEffect(() => {
//Runs on every render
});

An empty array
useEffect(() => {
//Runs only on the first render
}, []);

Props or state values


useEffect(() => {
//Runs on the first render
//And any time any dependency value changes
}, [prop, state]);

import { useState, useEffect } from "react";


import ReactDOM from "react-dom/client";

function Counter() {
const [count, setCount] = useState(0);
const [calculation, setCalculation] = useState(0);

useEffect(() => {
setCalculation(() => count * 2);
}, [count]); // <- add the count variable here

return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>+</button>
<p>Calculation: {calculation}</p>
</>
);
}
Unit-3: Forms and Hooks in React.JS
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);

Effect Cleanup
• Some effects require cleanup to reduce memory leaks.
• Timeouts, subscriptions, event listeners, and other effects that are no
longer needed should be disposed.
• A return function at the end of the useEffect Hook.
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

function Timer() {
const [count, setCount] = useState(0);

useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);

return () => clearTimeout(timer)


}, []);

return <h1>I've rendered {count} times!</h1>;


}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Timer />);

useContext
• To set the global data and this data can now be accessed in any of the
children’s components without the need to pass it through every parent
Component.
• Syntax
const authContext = useContext(initialValue);
The use Context accepts the value provided
by React.createContext and then re-render the component whenever its
value changes but you can still optimize its performance by
using memoization.
AuthContext.js
import React from 'react';

const authContext = React.createContext({


auth: null,
login: () => {},
Unit-3: Forms and Hooks in React.JS
logout: () => {},
});
export default authContext;
App.jsx
import React, { useState } from 'react';
import LogIn from './Login';
import LogOut from './Logout';
import AuthContext from './AuthContext';

const App = () => {


const [auth, setAuth] = useState(false);
const login = () => {
setAuth(true);
};
const logout = () => {
setAuth(false);
};
return (
<React.Fragment>
<AuthContext.Provider
value={{ auth: auth, login: login}}
>
<p>{auth ? 'Hi! You are Logged In' : 'Oope! Kindly Login'}</p>
<LogIn />
</AuthContext.Provider>
</React.Fragment>
);
};
export default App;
Login.js
import React, { useContext } from 'react';
import AuthContext from './AuthContext';

const Login = () => {


const auth = useContext(AuthContext);
return (
<>
<button onClick={auth.login}>Login</button>
</>
);
Unit-3: Forms and Hooks in React.JS
};
export default Login;

3.2.2 useRef, useReducer, useCallback, useMemo


useRef
• The useRef Hook allows you to persist values between renders.
• It can be used to store a mutable value that does not cause a re-render
when updated.
• It can be used to access a DOM element directly.
• If we tried to count how many times our application renders using
the useState Hook, we would be caught in an infinite loop since this Hook
itself causes a re-render.
To avoid this, we can use the useRef Hook.

import { useState, useEffect, useRef } from "react";


import ReactDOM from "react-dom/client";

function App() {
const [inputValue, setInputValue] = useState("");
const count = useRef(0);

useEffect(() => {
count.current = count.current + 1;
});

return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h1>Render Count: {count.current}</h1>
</>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
Unit-3: Forms and Hooks in React.JS
root.render(<App />);

• useRef() only returns one item. It returns an Object called current.


• When we initialize useRef we set the initial value: useRef(0).

Accessing DOM Elements


import { useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
const inputElement = useRef();

const focusInput = () => {


inputElement.current.focus();
};

return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<App />);

useReducer

• The useReducer Hook is similar to the useState Hook.


• It allows for custom state logic.
• If you find yourself keeping track of multiple pieces of state that rely on
complex logic, useReducer may be useful.
Syntax

• The useReducer Hook accepts two arguments.

useReducer(<reducer>, <initialState>)

• The reducer function contains your custom state logic and the initial State
can be a simple value but generally will contain an object.
Unit-3: Forms and Hooks in React.JS
• The useReducer Hook returns the current state and a dispatch method.

import { useReducer } from "react";


import ReactDOM from "react-dom/client";

const initialTodos = [
{
id: 1,
title: "Todo 1",
complete: false,
},
{
id: 2,
title: "Todo 2",
complete: false,
},
];

const reducer = (state, action) => {


switch (action.type) {
case "COMPLETE":
return state.map((todo) => {
if (todo.id === action.id) {
return { ...todo, complete: !todo.complete };
} else {
return todo;
}
});
default:
return state;
}
};

function Todos() {
const [todos, dispatch] = useReducer(reducer, initialTodos);

const handleComplete = (todo) => {


dispatch({ type: "COMPLETE", id: todo.id });
};

return (
<>
{todos.map((todo) => (
<div key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.complete}
onChange={() => handleComplete(todo)}
/>
{todo.title}
Unit-3: Forms and Hooks in React.JS
</label>
</div>
))}
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Todos />);

useCallback
• The React useCallback Hook returns a memoized callback function.
• This allows us to isolate resource intensive functions so that they will not
automatically run on every render.
• The useCallback Hook only runs when one of its dependencies update.
• This can improve performance.
• One reason to use useCallback is to prevent a component from re-
rendering unless its props have changed.

index.js

import { useState } from "react";


import ReactDOM from "react-dom/client";
import Todos from "./Todos";

const App = () => {


const [count, setCount] = useState(0);
const [todos, setTodos] = useState([]);

const increment = () => {


setCount((c) => c + 1);
};
const addTodo = () => {
setTodos((t) => [...t, "New Todo"]);
};

return (
<>
<Todos todos={todos} addTodo={addTodo} />
<hr />
Unit-3: Forms and Hooks in React.JS
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<App />);

Todos.js
import { memo } from "react";

const Todos = ({ todos, addTodo }) => {


console.log("child render");
return (
<>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
<button onClick={addTodo}>Add Todo</button>
</>
);
};

export default memo(Todos);

useMemo
• The React useMemo Hook returns a memorized value.
• The useMemo Hook only runs when one of its dependencies update.
• This can improve performance.
• The useMemo Hook can be used to keep expensive, resource intensive
functions from needlessly running.

import { useState, useMemo } from "react";


import ReactDOM from "react-dom/client";

const App = () => {


Unit-3: Forms and Hooks in React.JS
const [count, setCount] = useState(0);
const [todos, setTodos] = useState([]);
const calculation = useMemo(() => expensiveCalculation(count), [count]);

const increment = () => {


setCount((c) => c + 1);
};
const addTodo = () => {
setTodos((t) => [...t, "New Todo"]);
};

return (
<div>
<div>
<h2>My Todos</h2>
{todos.map((todo, index) => {
return <p key={index}>{todo}</p>;
})}
<button onClick={addTodo}>Add Todo</button>
</div>
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
<h2>Expensive Calculation</h2>
{calculation}
</div>
</div>
);
};

const expensiveCalculation = (num) => {


console.log("Calculating...");
for (let i = 0; i < 1000000000; i++) {
num += 1;
}
return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));


Unit-3: Forms and Hooks in React.JS
root.render(<App />);

3.2.3 Hook: Building custom hook, advantages and use

• React.Js provides lots of built-in hooks that you can use in your React
apps.
• You can make your own custom hooks and use it in your apps resulting
in better readability and a reduced amount of code.
• Custom hooks are normal JavaScript functions whose names start with
“use” and they may call other hooks(built-in or custom).
Custom hooks give us following benefits:

• Completely separate logic from user interface.


• Reusable in many different components with the same processing logic.
Therefore, the logic only needs to be fixed in one place if it changes.
• Share logic between components.
• Hide code with complex logic in a component, make the component
easier to read.

When to use React custom hook?

• When a piece of code (logic) is reused in many places (it’s easy to see
when you copy a whole piece of code without editing anything, except
for the parameter passed. Split like how you separate a function).
• When the logic is too long and complicated, you want to write it in
another file, so that your component is shorter and easier to read
because you don’t need to care about the logic of that hook anymore.

Building a custom hook:


Unit-4: Angular JS

4.1 Concepts and characteristics of Angular JS


• Angular JS is an open-source JavaScript framework that is used to build
web applications. It can be freely used, changed and shared by anyone.
• AngularJS is a JavaScript framework for building MVC-based web
applications. It allows you to split the business logic layer, data layer, and
presentation layer.
• Angular JS is developed by Google.
• It is an excellent framework for building single phase applications and line
of business applications.
• It uses HTML as a template language to extend its syntax for creating
various application components. It also helps to reduce the code by data
binding and dependency injection features.

Features

• MVC – The framework is built on the famous concept of MVC (Model-


View-Controller). This is a design pattern used in all modern-day web
applications. This pattern is based on splitting the business logic layer, the
data layer, and presentation layer into separate sections. The division into
different sections is done so that each one could be managed more easily.

• Data Model Binding – You don’t need to write special code to bind data
to the HTML controls. This can be done by Angular by just adding a few
snippets of code.

• Writing less code – When carrying out DOM manipulation a lot of


JavaScript was required to be written to design any application. But with
Angular, you will be amazed with the lesser amount of code you need to
write for DOM manipulation.
• Unit Testing ready – The designers at Google not only developed Angular
but also developed a testing framework called “Karma” which helps in
designing unit tests for AngularJS applications.

4.1.1 Expressions in Angular JS (Numbers, Strings, Objects,


Arrays)
Unit-4: Angular JS

• In AngularJS, expressions are used to bind application data to HTML.


AngularJS resolves the expression, and return the result exactly where the
expression is written.
• Expressions are written inside double braces {{expression}}.They can also
be written inside a directive: ng-bind="expression".
• Example: {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Numbers
AngularJS numbers are similar to JavaScript numbers.
<!DOCTYPE html>
<html>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></
script>
<body>
<div ng-app="" ng-init="quantity=5;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
</body>
</html>

We can use the same example by using ng-bind:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="quantity=5;cost=5">
<p>Total in dollar: <span ng-
bind="quantity * cost"></span></p>
</div>
</body>
</html>
Unit-4: Angular JS

Strings
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='Sonoo';lastName='Jaiswal'">
<p>My full name is: {{ firstName + " " + lastName }}</p>
</div>
</body>
</html>

Objects
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-
init="person={firstName:'Sonoo',lastName:'Jaiswal'}">
<p>My name is {{ person.firstName }}</p>
</div>
</body>
</html>

Arrays
<!DOCTYPE html>
<html>
Unit-4: Angular JS

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/an
gular.min.js"></script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The first result is {{ points[0] }}</p>
</div>
</body>
</html>

4.1.2 Setting up Environment, Angular JS Filters


Environment Setup
• First download the script file from https://angularjs.org/
• Click on Download AngularJS 1 image.

• You can download the AngularJS script file, when you click on download
button. You can download Minified, Uncompressed or in Zip file format.
• If you downloaded the zip file, then unzip it and copy and paste
angularjs.min.js file in your visual studio project folder.

Angular JS Filters
In AngularJS, filters are used to format data. Following is a list of filters used for
transforming data.

Filter Description

Currency It formats a number to a currency format.

Date It formats a date to a specified format.

Filter It select a subset of items from an array.

Json It formats an object to a Json string.


Unit-4: Angular JS

Limit It is used to limit an array/string, into a specified number of


elements/characters.

Lowercase It formats a string to lower case.

Number It formats a number to a string.

Orderby It orders an array by an expression.

Uppercase It formats a string to upper case.

How to add filters to expressions

• You can add filters to expressions by using the pipe character |, followed
by a filter.
• In this example, the uppercase filter format strings to upper case:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ firstName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "Sonoo",
$scope.lastName = "Jaiswal"
});
</script>
</body>
</html>

4.1 3 Understanding MVC (Model, View, Controller)


architecture
Unit-4: Angular JS

• MVC stands for Model View Controller.


• It is a software design pattern for developing web applications.
• It is very popular because it isolates the application logic from the user
interface layer and supports separation of concerns.

The MVC pattern is made up of the following three parts:

1. Model: It is responsible for managing application data. It responds to the


requests from view and to the instructions from controller to update
itself.
2. View: It is responsible for displaying all data or only a portion of data to
the users. It also specifies the data in a particular format triggered by the
controller's decision to present the data. They are script-based template
systems such as JSP, ASP, PHP and very easy to integrate with AJAX
technology.
3. Controller: It is responsible to control the relation between models and
views. It responds to user input and performs interactions on the data
Unit-4: Angular JS

model objects. The controller receives input, validates it, and then
performs business operations that modify the state of the data model.

4.2 AngularJS Directive (ng-app, ng-init, ng-controller, ng-


model, ng-repeat)
• 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.

ng-app
• 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.

<div ng-app = "">


...
</div>

ng-init
• 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.
Unit-4: Angular JS

<div ng-app = "" ng-init = "countries = [{locale:'en-


IND',name:'India'}, {locale:'en-PAK',name:'Pakistan'}, {locale:'en-
AUS',name:'Australia'}]">
...
</div>

ng-controller
• The AngularJS ng-controller directive adds a controller class to the view
(your application). It is the key aspect which specifies the principles
behind the Model-View-Controller design pattern.
• It facilitates you to write code and make functions and variables, which
will be parts of an object, available inside the current HTML element. This
object is called scope.
• This is supported by all HTML elements.
• Syntax <element ng-controller="expression"></element>

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "Aryan";
$scope.lastName = "Jaiswal";
});
</script>
Unit-4: Angular JS

<p>In this example you can see how to define a controller, and how to use vari
ables made for the scope.</p>
</body>
</html>

ng-model
• 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
• ng-repeat directive repeats html elements for each item in a collection. In
following example, we've iterated over array of countries.

<div ng-app = "">


...
<p>List of Countries with locale:</p>

<ol>
<li ng-repeat = "country in countries">
{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
</li>
</ol>
Unit-4: Angular JS

4.2.1 Some other directives: ng-class, ng-animate, ng-show,


ng-hide
ng-class
• The AngularJS ng-class directive facilitates you to dynamically set CSS
classes on an HTML element by databinding an expression that represents
all classes to be added.
• It may be a String, an object or an array.
• In case of a string, it should contain one or more, space-separated class
names.
• In case of an object, it should contain key-value pairs, where the key is the
class name of the class you want to add, and the value is a Boolean value.
• In the case of an array, it can be a combination of both.
• <element ng-class="expression"></element>
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<style>
.normal {
color:white;
background-color:grey;
padding:20px;
font-family:"Courier New";
}
.medium {
color:white;
background-color:brown;
padding:30px;
font-family:"Courier New";
}
.advance {
background-color:red;
padding:40px;
Unit-4: Angular JS

font-family:Verdana;
}
</style>
<body ng-app="">
<p>Choose a class:</p>
<select ng-model="home">
<option value="normal">Normal</option>
<option value="medium">Medium</option>
<option value="advance">Advance</option>
</select>
<div ng-class="home">
<h1>Hello</h1>
<p>World</p>
</div>
</body>
</html>

ng-animate
• In angularjs ngAnimate module will provide a CSS based animation
transitions effect to elements while performing show/hide or fade in /
fade out, etc. events.
• In angularjs ngAnimate module will add/remove some pre-defined CSS
classes to HTML elements to provide animation effect whenever certain
events raised like show/hide elements.
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Animations Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/angular
js/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angular
js/1.4.8/angular-animate.js"></script>
<script type="text/javascript">
var app = angular.module("angularapp", ["ngAnimate"]);
</script>
Unit-4: Angular JS

<style>
div
{
transition: all linear 0.5s;
background-color: #08c;
width: 30%;
padding:30px;
border:1px solid black;
}
.ng-hide {
opacity:0;
}
</style>
</head>
<body ng-app="angularapp">
<h2>AngularJS Animations Example</h2>
Show / Hide Div <input type="checkbox" ng-
model="chkselct"><br /><br />
<div ng-hide='chkselct' style="clear:both;">Hi Welcome to
Angularjs... Hello World</div>
</body>
</html>

The following are some of the directives that supports animation effect.

• ng-repeat
• ng-view
• ng-include
• ng-show / hide
• ng-switch
• ng-if
• Whenever ng-show / hide events raised ngAnimate module is used ng-
hide class to add/remove animation effect.

• The other directives use ng-enter and ng-leave classes to add/remove


the animation effect for HTML elements.

• This is how we can implement an animation effect to the elements in


angularjs applications using the ngAnimate module.
Unit-4: Angular JS

ng-show
• The AngularJS ng-show directive is used to show or hide the given HTML
element according to the expression given to the ng-show attribute.
• It shows the specified HTML element if the given expression is true,
otherwise it hides the HTML element.

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body ng-app="">
Show HTML element: <input type="checkbox" ng-model="myVar">
<div ng-show="myVar">
<h1>Hello</h1>
<p>Class.</p>
</div>
</body>
</html>

ng-hide
• The AngularJS ng-hide directive is used to hide the HTML element if the
expression is set to true.
• The element is shown if you remove the ng-hide CSS class and hidden, if
you add the ng-hide CSS class onto the element. The ng-hide CSS class is
predefined in AngularJS and sets the element's display to none.
• <element ng-hide="expression"></element>

As a CSS class:

• <element class="ng-hide"></element>
<!DOCTYPE html>
<html>
Unit-4: Angular JS

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js
"></script>
<body ng-app="">
Hide HTML: <input type="checkbox" ng-model="myVar">
<div ng-hide="myVar">
<h1>Welcome </h1>
<p>A solution of all technologoes.</p>
</div>
</body>
</html>

4.2.2 Expressions and Controllers


• AngularJS application mainly relies on controllers to control the flow of
data in the application.
• A controller is defined using ng-controller directive.
• A controller is a JavaScript object that contains attributes/properties, and
functions.
• Each controller accepts $scope as a parameter, which refers to the
application/module that the controller needs to handle.
<div ng-app = "" ng-controller = "studentController">
...
</div>

Here, we declare a controller named studentController, using the ng-


controller directive. We define it as follows –

<script>
function studentController($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

fullName: function() {
var studentObject;
Unit-4: Angular JS

studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
}
</script>
• The studentController is defined as a JavaScript object with $scope as
an argument.
• The $scope refers to application which uses the studentController
object.
• The $scope.student is a property of studentController object.
• The firstName and the lastName are two properties of $scope.student
object. We pass the default values to them.
• The property fullName is the function of $scope.student object, which
returns the combined name.
• In the fullName function, we get the student object and then return the
combined name.
• As a note, we can also define the controller object in a separate JS file
and refer that file in the HTML page.

Example:
<html>
<head>
<title>Angular JS Controller</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>

<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "studentController">


Enter first name: <input type = "text" ng-model = "student.firstName"><br>
<br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>

<script>
var mainApp = angular.module("mainApp", []);
Unit-4: Angular JS

mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>

</body>
</html>

4.2.3 Filters (Uppercase, Lowercase, Currency, order by)


Uppercase
The uppercase filter converts the string to upper case.
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
<div ng-
init="person.firstName='James';person.lastName='Bond'">
Upper case: {{person.firstName + ' ' + person.lastName |
uppercase}}
</div>
</body>
</html>

Lowercase
The lowercase filter converts the string to lower case.
Unit-4: Angular JS

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
<div ng-
init="person.firstName='James';person.lastName='Bond'">
Lower case: {{person.firstName + ' ' + person.lastName |
lowercase}} <br />
</div>
</body>
</html>

Currency
The currency filter formats a number value as a currency. When no currency
symbol is provided, default symbol for current locale is used.

{{ expression | currency : 'currency_symbol' : 'fraction'}}

<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
Default currency: {{person.salary | currency}} <br />
Custom currency identifier: {{person.salary |
currency:'Rs.'}} <br />
No Fraction: {{person.salary | currency:'Rs.':0}} <br />
Fraction 2: <span ng-bind="person.salary|
currency:'GBP':2"></span>
</div>
<script>
var myApp = angular.module('myApp', []);

myApp.controller("myController", function ($scope) {


$scope.person = { firstName: 'James', lastName: 'Bond',
salary: 100000}
});
</script>
</body>
Unit-4: Angular JS

</html>

order by
• The orderBy filter sorts an array based on specified expression predicate.
• {{ expression | orderBy : predicate_expression : reverse}}

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myController">
<select ng-model="SortOrder">
<option value="+name">Name (asc)</option>
<option value="-name">Name (dec)</option>
<option value="+phone">Phone (asc)</option>
<option value="-phone">Phone (dec)</option>
</select>
<ul ng-repeat="person in persons | orderBy:SortOrder">
<li>{{person.name}} - {{person.phone}}</li>
</ul>
</div>
<script>
var myApp = angular.module('myApp', []);

myApp.controller("myController", function ($scope) {

$scope.persons = [{ name: 'John', phone: '512-455-1276'


},
{ name: 'Mary', phone: '899-333-3345' },
{ name: 'Mike', phone: '511-444-4321' },
{ name: 'Bill', phone: '145-788-5678' },
{ name: 'Ram', phone: '433-444-8765' },
{ name: 'Steve', phone: '218-345-5678' }]

$scope.SortOrder = '+name';
});
</script>
</body>
</html>
Unit-5: Angular JS: Single page application

5.1 Single page application using AngularJS


5.1.1 Create a module, Define Simple controller
• The AngularJS module defines the functionality of the application which
is applied on the entire HTML page.
• It helps to link many components. So, it is just a group of related
components.
• It is a container which consists of different parts like controllers, services,
directives.
Note: This module should be made in a normal HTML file like index.html and
no need to create a new project in Visual Studio for this section.

How to create a Module:

var app = angular.module("Module-name", []);


In this [] we can add a list of components needed

<div ng-app = "module-name">


The code in which the module is required.
</div>

Adding a Controller:

app.controller("Controller-name", function($scope) {
$scope.variable-name= "";
});
Here, we can add any number of variables in controller and use them in the
html files, body of the tag in which the controller is added to that tag by
writing:
<body>
<div ng-app="Module-name">
<div ng-controller="Controller-name">
{{variable-name}}
</div>
Unit-5: Angular JS: Single page application

<!-- This wont get printed since its


not part of the div in which
controller is included -->
{{variable-name}}
</div>
</body>

Example:
DemoComponent.js
app.controller('DemoController', function($scope) {

$scope.list = ['A', 'E', 'I', 'O', 'U'];


$scope.choice = 'Your choice is: ';

$scope.ch = function(choice) {
$scope.choice = "Your choice is: " + choice;
};

$scope.c = function() {
$scope.choice = "Your choice is: " + $scope.mychoice;
};
});

Module-name: DemoApp.js
var app = angular.module('DemoApp', []);
index.html file
<!DOCTYPE html>
<html>

<head>
<title>
Modules and Controllers in Files
</title>
</head>

<body ng-app="DemoApp">
<h1>
Using controllers in Module
</h1>

<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js
">
Unit-5: Angular JS: Single page application
</script>

<script src="DemoApp.js"></script>
<script src="DemoController"></script>

<div ng-app="DemoApp" ng-controller="DemoController">


Vowels List : <button ng-click="ch('A')" >A</button>

<button ng-click="ch('E')" >E</button>


<button ng-click="ch('I')" >I</button>
<button ng-click="ch('O')" >O</button>
<button ng-click="ch('U')" >U</button>

<p>{{ choice }}</p>

Vowels List :
<select ng-options="option for option in list"
ng-model="mychoice" ng-change="c()">
</select>

<p>{{ choice }}</p>


</div>
</body>

</html>

5.1.2 Embedding AngularJS script in HTML


• Angular provides the function to include the functionality from other
AngularJS files by using the ng-include directive.

• The primary purpose of the “ng-include directive” is used to fetch,


compile and include an external HTML fragment in the main AngularJS
application.

Step 1)

• Write the below code in a file called Table.html. This is the file which will
be injected into our main application file using the ng-include directive.

• The below code snippet assumes that there is a scope variable called
“tutorial.” It then uses the ng-repeat directive, which goes through each
Unit-5: Angular JS: Single page application
topic in the “Tutorial” variable and displays the values for the ‘name’ and
‘description’ key-value pair.

<table>
<tr ng-repeat="Topic in tutorial">
<td>{{ Topic.Name }}</td>
<td>{{ Topic.Country }}</td>
</tr>
</table>

Step 2)

• let’s write the below code in a file called Main.html. This is a simple
angular.JS application which has the following aspects

1. Use the “ng-include directive” to inject the code in the external file
‘Table.html’. The statement has been highlighted in bold in the below
code. So the div tag ‘ <div ng-include=”‘Table.html'”></div>’ will be
replaced by the entire code in the ‘Table.html’ file.
2. In the controller, a “tutorial” variable is created as part of the $scope
object. This variable contains a list of key-value pairs.

In our example, the key value pairs are

1. Name – This denotes the name of a topic such as Controllers, Models,


and Directives.
2. Description – This gives a description of each topic

The tutorial variable is also accessed in the ‘Table.html’ file.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Event Registration</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
</head>
Unit-5: Angular JS: Single page application
<body ng-app="sampleApp">
<div ng-controller="AngularController">
<h3> Global Event</h3>
<div ng-include="'Table.html'"></div>
</div>
<script>

var sampleApp = angular.module('sampleApp',[]);


sampleApp.controller('AngularController', function($scope) {
$scope.tutorial =[
{Name: "Controllers" , Description : "Controllers in action"},
{Name: "Models" , Description : "Models and binding data"},
{Name: "Directives" , Description : "Flexibility of Directives"}
];

});
</script>
</body>
</html>

5.1.3 AngularJS’s routine capability


• Routing in AngularJS is one of the core feature. In this AngularJS routing
example, we will build a small single page application with multiple views
to show you how routing in AngularJS works.

ngRoute

• AngularJS ngRoute module provides routing, deep linking services and


directives for angular applications.

• We have to download angular-route.js script that contains the ngRoute


module from AngularJS official website to use the routing feature.

• You can also use the CDN in your application to include this file. In this
tutorial, We are going to use the Google
CDN. https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js If you are bundling this file into your application, then you
can add it to your page with below code.
Unit-5: Angular JS: Single page application
<script src="angular-route.js">

If you want to include it from Google CDN, then use below code.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js"></script>

Then load the ngRoute module in your AngularJS application by adding it as a


dependent module as shown below.

angular.module('appName', ['ngRoute']);

ngView

• ngView directive is used to display the HTML templates or views in the


specified routes.

• Every time the current route changes, the included view changes with it
according to the configuration of the $route service.

$routeProvider

• $routeProvider is used to configure the routes.

• We use the ngRoute config() to configure the $routeProvider.

• The config() takes a function which takes the $routeProvider as


parameter and the routing configuration goes inside the function.
$routeProvider has a simple API, accepting either
the when() or otherwise() method.

AngularJS Routing Syntax

The following syntax is used to configure the routes in AngularJS.

var app = angular.module("appName", ['ngRoute']);

app.config(function($routeProvider) {

$routeProvider

.when('/view1', {

templateUrl: 'view1.html',
Unit-5: Angular JS: Single page application
controller: 'FirstController'

})

.when('/view2', {

templateUrl: 'view2.html',

controller: 'SecondController'

})

.otherwise({

redirectTo: '/view1'

});

});

• when() method takes a path and a route as parameters.

• path is a part of the URL after the # symbol. route contains two properties
- templateUrl and controller.

• templateUrl property defines which HTML template AngularJS should


load and display inside the div with the ngView directive.

• controller property defines which controllers should be used with the


HTML template. When the application is loaded, path is matched against
the part of the URL after the # symbol.

• If no route paths matches the given URL the browser will be redirected to
the path specified in the otherwise() function.

AngularJS Routing Example

Now let’s go through a simple example to understand the AngularJS rounting.


At first, we will define a module, some routes, create controllers and create
multiple views. Finally, we will create the shell page of our application to hold
the multiple views.

1. Create a module named mainApp and load ngRoute as a dependent


module.
2. Configure the routes using $routeProvider.
Unit-5: Angular JS: Single page application
3. We use two paths in the example, /home and /viewStudents.
4. We use only a single controller in this example, StudentController
5. StudentController is initialized with an array of students and a message.
We will be showing the message in the home page and the students list
in viewStudents page.
6. Save this file as main.js

main.js

var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.config(function($routeProvider) {

$routeProvider

.when('/home', {

templateUrl: 'home.html',

controller: 'StudentController'

})

.when('/viewStudents', {

templateUrl: 'viewStudents.html',

controller: 'StudentController'

})

.otherwise({

redirectTo: '/home'

});

});

mainApp.controller('StudentController', function($scope) {

$scope.students = [
Unit-5: Angular JS: Single page application
{name: 'Mark Waugh', city:'New York'},

{name: 'Steve Jonathan', city:'London'},

{name: 'John Marcus', city:'Paris'}

];

$scope.message = "Click on the hyper link to view the students list.";

});

• For example, if the URL is


like https://www.journaldev.com/index.html#/home, The URL part after
the # matches /home, it will load home.html page and if it
matches /viewStudents then it will load viewStudents.html in to the shell
page.

• If nothing matches then it will go in otherwise condition and page will be


redirected to home.html. Now we can create our views and save
as home.html and viewStudents.html files. home.html

<div class="container">

<h2> Welcome </h2>

<p>{{message}}</p>

<a href="#/viewStudents"> View Students List</a>

</div>

This is the default page of our application. In this view, we just print out the
message, which we have already initialized in the StudentController. You can
also see a link to the viewStudents page. viewStudents.html

<div class="container">

<h2> View Students </h2>

Search:

<br/>
Unit-5: Angular JS: Single page application
<input type="text" ng-model="name" />

<br/>

<ul>

<li ng-repeat="student in students |


filter:name">{{student.name}} , {{student.city}}</li>

</ul>

<a href="#/home"> Back</a>

</div>

In the above view, you can see a list of students with a search option. Finally,
follow below steps to complete our AngularJS routing example application.

• ng-app auto-bootstraps our application mainApp


• ngView directive is the placeholder of the views
- home.html and viewStudents.html
• Include angular.min.js and angular-route.min.js
• Include main.js which we have created in the earlier steps.
• Save the file as index.html

index.html

<!DOCTYPE html>

<html>

<head lang="en">

<meta charset="utf-8">

<title>AngularJS Routing</title>

</head>

<body>
Unit-5: Angular JS: Single page application
<div ng-app="mainApp">

<ng-view></ng-view>

</div>

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></
script>

<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-
route.min.js"></script>

<script type="text/javascript" src="main.js"></script>

</body>

</html>

That’s all for our AngularJS Routing example. Our application is ready to run.

Run your application

• Save all the files in the same directory.


• open index.html from your browser

5.1.3.2 Navigating different pages


5.2 HTML DOM directives4
• The logical structure of documents and documents are accessed and
manipulated are defined using DOM elements.

• It defines events, methods, properties for all HTML elements as objects.


DOM in AngularJS acts as an API (programming interface) for javascript.

• Whenever a web page is loaded, the browser creates a Document Model


Object (DOM) of that page.
Unit-5: Angular JS: Single page application
A programmer can use DOM in AngularJS for the following purposes:

• Documents are built using DOM elements.


• A Programmer can navigate documents structure with DOM
elements.
• A programmer can add elements and content with DOM elements.
• Programmer can modify elements and content with DOM elements.

We can use various directives to bind the application data to the attributes of
DOM elements. Some of them are:
• ng-disabled
• ng-hide
• ng-click
• ng-show

5.2.1
ng-disabled
• We can use ng-disabled for disabling a given control. Attributes of HTML
elements can be disabled using ng-disabled directive.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "enableDisableButton">To disable a
button
<button ng-disabled = "enableDisableButton">Click</button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<body>
<div ng-app="" ng-init="value=true">
<p><button ng-disabled="value">Click Here!!</button></p>
<p><input type="checkbox" ng-model="value"/>Button</p>
<p>{{ value }}</p>
Unit-5: Angular JS: Single page application
</div>
</body>
</html>

• The ng-model directive binds the value of the HTML checkbox element to
the value of value (In the above code value is the name of application
data).

• If the value of value evaluates to true, the button will disable and if the
value of value evaluates to false, the button will not disable

ng-show
• We can use ng-show for showing a given control.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "showHide1">To show a Button
<button ng-show = "showHide1">Click </button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<body>
<div ng-app="">
<input type = "checkbox" ng-model = "showhiddenbutton">Show button
<button ng-show = "showhiddenbutton">Click Here!</button>
</div>
</body>
</html>
Unit-5: Angular JS: Single page application
• When the checkbox is checked the output displays a button of click
here! also.

Output-
(checked) Show button Click Here!

ng-hide
• We can use ng-hide for hiding a given control.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<input type = "checkbox" ng-model = "showHide2">To hide a Button
<button ng-hide = "showHide2">Click</button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<div ng-app="">
<input type = "checkbox" ng-model = "hidebutton">Hide Button
<button ng-hide = "hidebutton">Click Here!</button>
</div>
</body>
</html>

Output-
__ Hide Button Click Here!

When you checked the checkbox, the button click here! will get hidden.

ng-click
Unit-5: Angular JS: Single page application
• We can use ng-click for representing an angularjs click event.

• We can use it by adding it to an HTML button and pass it to model

Syntax
<p>Number of click: {{ clickCounter }}</p>
<button ng-click = "clickCounter = clickCounter + 1">Click </button>

Example
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"
></script>
<div ng-app="">
<p>Total number of Clicks: {{ Counts }}</p>
<button ng-click = "Counts = Counts+ 1">Click Here!</button>
</div>
</body>
</html>

• The number of times you will click on the button Click Here! will get
displayed corresponding to the total number of clicks.

5.2.2 Modules (Application, Controller)


5.2.3 Forms (Events, Data validation, ng-click)
AngularJS facilitates you to create a form enriches with data binding and
validation of input controls.

Input controls are ways for a user to enter data. A form is a collection of controls
for the purpose of grouping related controls together.

Following are the input controls used in AngularJS forms:

o input elements
o select elements
Unit-5: Angular JS: Single page application
o button elements
o textarea elements

AngularJS provides multiple events that can be associated with the HTML
controls. These events are associated with the different HTML input elements.

Following is a list of events supported in AngularJS:

o ng-click
o ng-dbl-click
o ng-mousedown
o ng-mouseup
o ng-mouseenter
o ng-mouseleave
o ng-mousemove
o ng-mouseover
o ng-keydown
o ng-keyup
o ng-keypress
o ng-change

Example:

<!DOCTYPE html>
<html>
<head>
<title>Angular JS Forms</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/
angular.min.js"></script>

<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
Unit-5: Angular JS: Single page application
table tr:nth-child(odd) {
background-color: lightpink;
}

table tr:nth-child(even) {
background-color: lightyellow;
}
</style>

</head>
<body>

<h2>AngularJS Sample Application</h2>


<div ng-app = "mainApp" ng-controller = "studentController">

<form name = "studentForm" novalidate>


<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input name = "firstname" type = "text" ng-
model = "firstName" required>
<span style = "color:red" ng-
show = "studentForm.firstname.$dirty && studentForm.firstname.$inv
alid">
<span ng-
show = "studentForm.firstname.$error.required">First Name is require
d.</span>
</span>
</td>
</tr>

<tr>
<td>Enter last name: </td>
<td><input name = "lastname" type = "text" ng-
model = "lastName" required>
Unit-5: Angular JS: Single page application
<span style = "color:red" ng-
show = "studentForm.lastname.$dirty && studentForm.lastname.$inva
lid">
<span ng-
show = "studentForm.lastname.$error.required">Last Name is required
.</span>
</span>
</td>
</tr>

<tr>
<td>Email: </td><td><input name = "email" type = "email" n
g-model = "email" length = "100" required>
<span style = "color:red" ng-
show = "studentForm.email.$dirty && studentForm.email.$invalid">
<span ng-
show = "studentForm.email.$error.required">Email is required.</span
>
<span ng-
show = "studentForm.email.$error.email">Invalid email address.</spa
n>
</span>
</td>
</tr>

<tr>
<td>
<button ng-click = "reset()">Reset</button>
</td>
<td>
<button ng-disabled = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid || studentForm.lastname
.$dirty &&
studentForm.lastname.$invalid || studentForm.email.$dir
ty &&
studentForm.email.$invalid" ng-
click="submit()">Submit</button>
Unit-5: Angular JS: Single page application
</td>
</tr>

</table>
</form>
</div>

<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
$scope.firstName = "Sonoo";
$scope.lastName = "Jaiswal";
$scope.email = "[email protected]";
}

$scope.reset();
});
</script>

</body>
</html>

Data validation
AngularJS provides client-side form validation. It checks the state of the form
and input fields (input, textarea, select), and lets you notify the user about the
current state.

It also holds the information about whether the input fields have been touched,
or modified, or not.

Following directives are generally used to track errors in an AngularJS form:

o $dirty - states that value has been changed.


Unit-5: Angular JS: Single page application
o $invalid - states that value entered is invalid.
o $error - states the exact error.

Directive Description
ng-required Sets required attribute on an input field.
ng- Sets minlength attribute on an input field.
minlength
ng- Sets maxlength attribute on an input field. Setting the attribute to a
maxlength negative or non-numeric value, allows view values of any length.
ng-pattern Sets pattern validation error key if the ngModel value does not match
the specified RegEx expression.

<!DOCTYPE html>
<html>
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app >
<form name="studentForm" novalidate>
<label for="firstName">First Name: </label> <br />
<input type="text" name="firstName" ng-model="student.firstName"
ng-required="true" />
<span ng-show="studentForm.firstName.$touched &&
studentForm.firstName.$error.required">First name is required.</span><br
/><br />
<label for="lastName">Last Name</label><br />
<input type="text" name="lastName" ng-minlength="3" ng-
maxlength="10" ng-model="student.lastName" />
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.minlength">min 3 chars.</span>
<span ng-show="studentForm.lastName.$touched &&
studentForm.lastName.$error.maxlength">Max 10 chars.</span><br /><br />
<label for="dob">Email</label><br />
<input type="email" id="email" ng-model="student.email"
name="email" />
Unit-5: Angular JS: Single page application
<span ng-show="studentForm.email.$touched &&
studentForm.email.$error.email">Please enter valid email id.</span><br
/><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
SDJ INTERNATIONAL COLLEGE,PALSANA

IMPORTANT QUESTION BANK

ADVANCED WEB DESIGNING

Q.1 Short Questions:


1. What is AngularJS expressions?
2. What is a list?
3. What do you mean by Unstructured data?
4. What is ng-init?
5. What is the use of event.target.name?
6. What is aggregation in MongoDB?
7. What is the use of $routeProvider in AngularJS?
8. What is MVC?
9. What is a spread operator?
10.What is the difference between find() and findOne()?
11.What is a document in MongoDB? Explain with example.
12.What are the data types in MongoDB? List out any three.
13.Which method is used to add data in MongoDB? State the difference between
insertOne and insertMany.
14.What is the full form of JSX? Why JSX is used with React?
15.What is MVC?
16.What is create-react-app? Why is it used?
17.What is props in ReactJS?
18.What is data binding in AngularJS?
19.What is currency filter in AngularJS?
20.What is the use of $routeProvider service of ngRoute?
21.In which format does MongoDB represent document structure? Explain with an
example.
22.Is MongoDB better than other SQL databases? If yes, then how?
23.Explain React List.
24.What are components in React JS? List them out.
25.List out advantages of React.
26.How to build a custom hook?
27.What is Angular JS? List out any two features of it.
28.What are directives? Give names of two commonly used directives in Angular
JS.
29.What is the order by filter in Angular JS?
30.What is a module in Angular JS? Write syntax to create a module.

Q.2 Long Questions:

1. Explain operators of MongoDB in detail.


2. Explain MongoDB Data types in detail.
3. Explain React Components in detail. 
OR
What is a component in React? How can you embed two or more components
into one? Explain with a suitable code
4. Explain React hooks in detail.
5. Explain the Text Area and Drop-down List elements of React in detail.
6. Explain filters and Controller of AngularJS in detail.
7. What is DOM? Explain Directives in detail.
8. Explain features of AngularJS in detail.
9. Explain ng-app, ng-model, and ng-bind directive with example.
10.What is MongoDB? What are the advantages of MongoDB? Differentiate
NoSQL and SQL.
OR
What is MongoDB? What are the advantages of MongoDB? Explain Document
and Collection with an example.

11. Explain the concept of Form and Form validation in AngularJS. Write a suitable
code for the same.  
12.Explain the following MongoDB Query Document operations with syntax and
example:

a. find()
b. Pretty()
c. findOne()
d. And keyword
e. Or keyword

OR

Explain various insert operations of MongoDB.


13.Explain useRef, useReducer hooks with example.
14. What are services in AngularJS? Explain with an example. 
15.What is an event in React? How do you create it? Explain an event with an
example.
16.What are services in Angular JS? Explain with an example.
17.Explain useState and useContext hooks with examples.
18.What do you mean by expressions in Angular JS?

Q. 3 Write command/query for following MongoDB operations :


A.

1. Write a query to create "student" collection in the current database.


2. Write a query to insert five students' details into "student" collection.
3. Write a query to display students' names from "student" collection.
4. Write a query to display top 3 students' Roll no from "student" collection.
5. Write a query to display students' details with highest and lowest marks
from "student" collection.

B.
1. Create Database "University"
2. Create Collection named "private"
3. Create Collection named "central_uni"
4. Insert at least 2 documents in the collection "private" and in collection
"central_uni"
5. Delete the private university having name "C.J. Shah"
6. Find central_uni university named "J.R.Roy"
7. Update the "contact no" of central uni university where c_id is "101"
8. Delete all private university from "private" collection who have category
under the "fake" list
C.
1. Create Database "movie"
2. Create Collection named "film"
3. Create Collection named "actor"
4. Insert at least 2 documents in the collection film and in collection actor
5. Delete the film "XYZ"
6. Delete an actor named "ABC"
7. Update the actor's address where actor id is "101"
8. Delete all actors from an "actor" collection who have age greater than
"50"
Q.4 Write a code for following:

1. Write an AngularJS, which accepts and validates Student Name, Email Address,
and Mobile No from the user.
2. Create a Form in React.js for Student Registration, with Name, DOB, and
password. Display the details also.
3. Create a Simple counter using React.js, which increments or decrements count
dynamically on-screen as the user clicks on buttons. Use following steps:

I. Prepare two HTML buttons, one for increment value and other for
decrement value.
II. If we click on increment button then value will be increased by 1 (e.g., 1,
2, 3, 4...).
III. If we click on decrement button then value will be decreased by 1 (e.g., 4,
3, 2, 1...).

4. Write an angular JS code to display FirstName and LastName entered by the


user into the respective textboxes and display output in following form:
First name: Robert
Last name: Desoza
Hello Robert Desoza
5. Write a code using React.js, which displays "Hello World".
6. Write an Angular JS code, which accepts and validates "Name" and "Mobile
No" from the user.
7. Create a form in React.js with a Language Selection label, a Drop Down List
containing different Languages, and a Submit button component.

Q.5 Short Notes:

1. Operators in MongoDB
2. React JS Events
3. SPA (Single Page Application) in Angular JS
4. Angular JS Expressions and controllers
5. MongoDB datatypes with its syntax and example.
6. Hooks in React JS
7. MVC Architecture
8. Filters in Angular js
9. CRUD Operations
10.React Events
11.MVC Architecture
12.Props with Example

***ALL TH BEST***
SDJ INTERNATIONAL COLLEGE, PALSANA.

ADVANCED WEB DESIGNING

MONGODB COMMANDS OR QUERY

Write command/query for following MongoDB operations :


Q.1
1. Create Database "University"
use University

2. Create Collection named "private"


db.createCollection("private")

3. Create Collection named "central_uni"


db.createCollection("central_uni")

4. Insert at least 2 documents in the collection "private" and in collection


"central_uni"
PRIVATE:
db.private.insertMany([
{ name: "C.J. Shah", location: "City A", category: "legit",
c_id: "201" },
{ name: "A.B. Patel", location: "City B", category: "fake",
c_id: "202" }
])

CENTRAL_UNI
db.central_uni.insertMany([
{ name: "J.R. Roy", location: "City C", contact_no:
"1234567890", c_id: "101" },
{ name: "M.S. Sharma", location: "City D", contact_no:
"9876543210", c_id: "102" }
])
5. Delete the private university having name "C.J. Shah"
db.private.deleteOne({ name: "C.J. Shah" })

6. Find central_uni university named "J.R.Roy"


db.central_uni.find({ name: "J.R. Roy" })

7. Update the "contact no" of central uni university where c_id is "101"
db.central_uni.updateOne(
{ c_id: "101" },
{ $set: { contact_no: "1112223334" } }
)

8. Delete all private university from "private" collection who have


category under the "fake" list.
db.private.deleteMany({ category: "fake" })

Q.2
1. Create Database "movie"
use movie

2. Create Collection named "film"


db.createCollection("film")

3. Create Collection named "actor"


db.createCollection("actor")

4. Insert at least 2 documents in the collection film and in collection actor


FILM:
db.film.insertMany([
{ title: "XYZ", genre: "Action", release_year: 2023 },
{ title: "ABC", genre: "Drama", release_year: 2022 }
])
ACTOR:
db.actor.insertMany([
{ name: "ABC", age: 45, actor_id: "101", address: "123 Street"
},
{ name: "DEF", age: 55, actor_id: "102", address: "456
Avenue" }
])

5. Delete the film "XYZ"


db.film.deleteOne({ title: "XYZ" })

6. Delete an actor named "ABC"


db.actor.deleteOne({ name: "ABC" })

7. Update the actor's address where actor id is "101"


db.actor.updateOne(
{ actor_id: "101" },
{ $set: { address: "789 New Street" } }
)
8. Delete all actors from an "actor" collection who have age greater than
"50"
db.actor.deleteMany({ age: { $gt: 50 } })

Q.3

1. Write a query to create "student" collection in the current database.

db.createCollection("student")

2. Write a query to insert five students' details into "student"


collection.

db.student.insertMany([

{ name: "John Doe", roll_no: 1, marks: 85, age: 20 },

{ name: "Jane Smith", roll_no: 2, marks: 90, age: 21 },

{ name: "Alice Johnson", roll_no: 3, marks: 75, age: 19 },


{ name: "Bob Brown", roll_no: 4, marks: 65, age: 22 },

{ name: "Charlie Davis", roll_no: 5, marks: 95, age: 20 }

])

3. Write a query to display students' names from "student" collection.

db.student.find({}, { name: 1, _id: 0 })

4. Write a query to display top 3 students' Roll no from "student"


collection.

db.student.find({}, { roll_no: 1, _id: 0 }).limit(3)

5. Write a query to display students' details with highest and lowest


marks from "student" collection.

Student with highest marks:

db.student.find().sort({ marks: -1 }).limit(1)

Student with lowest marks:

db.student.find().sort({ marks: 1 }).limit(1)

You might also like