ITINERARY
HTML-4(4 days)
CSS-2
HTML-5
CSS-3
Bootstrap (2 days)
JavaScript (2 days)
Programming fundamentals (6 days)
o SDLC
o Flowcharts
o Algorithms
o DBMS
o SQL server
C# (16 days)
Advance C# (13 days)
Web programming (12 days)
type script (2 days)
Angular (8 days)
RLL PROJECT (7 days) - web programming
Web Servers and Web Browsers
Website (Web application)
1. Client-side programming
2. Server-side programming
Client-side programming
All programs are handled by web browser.
Parser checks the syntax (built in browser).
Eg: HTML, CSS, JS, XML, JSON
HTML: To create layout for website
CSS: To apply styles for website
JS: To apply validation for website (ex: check whether there are 10 digits in a
phone number)
XML: Data transfer into one language to another language (ex: c# - Java)
JSON: Like XML, but more compact
Drawbacks of Client-side programming
o No database support
o Not secure (source code is visible)
o Lacks framework support (no classes and methods)
Server-side programming
All programs are handled by web server (a software). Some of the
web servers are Apache, XAMP, IIS, Kestral, IISEXPRESS
Web Server
o The primary purpose of webserver is to host the webpages
o Hosting – Making the page which is available publicly (ISS >
System Name (top left) > sites> Default website > right click to
add application > enter alias and path)
o To open the public file, use the format - https://alias/filename
File:///D:/HTMLDEMO/HELLO.HTML - physical path
https://localhost/mphasis/hello.html - virtual path
o Web servers are also used to process server-side language.
Eg: PHP, NODEJS, JAVA, Python
o Browser doesn’t know server-side languages.
o All the server-side languages are executed by webservers.
Web Server has built-in compiler.
o The HTTP.SYS file checks whether it is client side or server-side
programming
o Webservers are also used to
create domain names. Eg: WWW.Facebook.com
to handle security
to handle cache
Basics of HTML-4
HTML – Hypertext Markup Language
Markup Language – Markup means highlighting
HTML is based on Standard Generalized Markup language (SGML). All the
HTML tags are created and developed using SGML (Mother of Markup
languages). Other markup languages: XML, WML
HTML is encoding language
It consists of tags and elements.
o <b> - tag
o tag + property + content – element eg: <font color = red>
Should have extension .htm or .html
Tags are not case sensitive
Basic Syntax
<html>
<head>
<title> Mphasis </title>: title appears as the tab name
</head>
<body>
Hello World
</body>
</html>
Doctype – to intimate the browser the version
Metatag – automatic refresh, search engine optimization
<meta refresh = 10> description = “a page displays current stock price”/>
When to go for head tag and when to go for body tag?
o Head tag has a priority than the body tag.
o Content in the head tag will be executed first followed by content
in the body tag.
Properties of the elements:
Bgcolor – background color
Background – background image
Text = color – text color
Margin – spacing from the axis
Anchor elements:
HREF – Path of the file to be opened
TARGET – Indicates in which frame the link opens
CLASS – To apply CSS style sheet
NAME – Internal Hyperlink
Sample codes:
Has two sections which can be redirected to with a click
<html>
<body leftmargin=50 bgcolor=black text=red>
<h1> Hello World </h1>
<a href="#sp"> Sports</a>
<a href="#ms">Music</a>
<br>
<a name="sp">
CSK vs MI
</a>
<br>
<a name="ms">
Carnatic
</a>
</body>
</html>
Redirect to another page and a also a particular part of the page
<html>
<body>
<a href= "basic.html#sp"> Click here </a>
</body>
</html>
Frame: Using frame, you can display content from multiple pages in a single
browser.
Two tags used to access frame:
<frameset> - use to set whether the content will be displayed in rows or
columns and set the orientation.
<frame> - used to set which page to be displayed
Note: while using frame tag, never use other tags. (no start or head or
body tag)
Sample code:
<frameset rows="30%,*">
<frame src="Birthday.html" />
<frame src="Home.html" />
</frameset>
Tags:
Tags can be of two types:
Inline tags – without line break. Eg: <b> <font> <i> </u> <img>
<span> <sub> <sup> <strike>
Block tags – with line break. Eg: <div> <table> <article> <section>
</header></footer><p><list><h1…h6>
Formatting Tags:
<h1> to <h6> - heading
<font> - text with attributes size, face, color, face (font style)
<b> - bold
<u> - underline
<i>- italic
List Tags:
Two types of lists:
Ordered List - <ol type = A, I>
Unordered List - <ul type = disc, circle, disc>
Sample codes:
<ul type = disc>
<li> Candy </li>
<li> Chocolate </li>
<li> Cherry </li>
</ul>
<ol type = A>
<li> Apple </li>
<li> Guava </li>
<li> Berry </li>
</ol>
</body>
<html>
Image tags:
Formart: <img src= “Image link” properties />
Eg: <img src = "https://tse4.mm.bing.net/th/id/OIP.-
OPlR_eRVYNy5IbdXCW5rwHaDt?w=315&h=174&c=7&r=0&o=5&pid=1.7"
height=200 width=200 />
Table tags:
<tr>
<th>
<td>
Sample code:
<table border =1bgcolor = pink algin = center cellpadding =20
cellspacing=10 height=25 width=10>
<tr>
<th> Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
<tr>
<td> Data1</td>
<td>Data 2</filltd>
<td>Data 3</td>
</tr>
Basics of CSS
CSS – Cascading Style Sheet
Drawbacks of HTML
Limited font styles
Limited support for bullets
Limited support for border
Limited support for customizing images
Limited attributes
No animation support
Not reusable – cannot apply same style for multiple pages
CSS
Developed in the year 1997
Using CSS, you can apply look and feel to the webpages
CSS allows to store content and formatting information in a separate
file.
How to work with CSS?
Analyze the type of CSS to be used. Types of CSS are:
Inline CSS – a style rule is applied only to a specific tag
Internal CSS (embedded) – a style rule is applied for entire document
(single document)
External CSS – a style rule is applied for all the document
How to work with inline?
Using style attribute
How to work with internal?
Using style tag
How to work with external?
By creating separate CSS file
Style Tag:
“style” is where the CSS attributes start
Syntax:
tag
Property: Value;
Inline CSS:
Use style tag inside the tag
Eg: <p style color = “red”>
Internal CSS:
Use style tag separately
Eg: <style>
Color:”blue”
External CSS - Incorporating external CSS file to HTML:
Syntax:
<head>
<link rel="stylesheet" href="file.css">
</head>
link – used to create icon file and link the file
Selectors in CSS:
element selector: CSS rules applied using element name.
Eg: p
Color:”blue”
id: Using a hashtag followed by an id name. Can only be used for a
specific tag
Eg: #hi
color:green;
while using in HTML - id="hi"
class: Using a dot followed by a name. Can be used for using same
rule for multiple tags
Eg: .mycls
color:green;
while using in HTML - class="mycls"
position:
Eg: p > b
{
color:green;
green color is applied to the b tag, but p must be child of b
Eg: p, b, h1
color:green;
applies color for all the mentioned tag
Eg: p+b
color:green;
applies style for b tag, but previous tag must be p tag
p[name] – tag containing attribute name
p[name=’King”]
p[name^=’King’]-tags starting the name King
p[name$=’King’]- tags ending the name King
p[name*=’King’]- tags that has the name King anywhere
p: nth-child (2) – apply style for 2nd paragraph child
Eg: p: nth - child (2)
color:green;
Background Image Tags in CSS:
color <color>
background-color transparent<color>
background-image none
url(<img ur>)
background-repeat repeat
repeat – x
repeat – y
no-repeat
background-attachment scroll
fixed
background-size Cover
Text tags in CSS:
CSS box Model:
Content
Padding
Border
Margin
Margin:
Left - margin-left:200px;
Right - margin-right:200px;
Top - margin-top:150px;
All for side - margin: 10 50 110 10;(top right down left)
Border:
Border color – border-color:5px;
Border width – border-color:green;
Border style- border-style: solid, dotted, dashed, double, groove
For combinations of styles:
border-top-style: dotted;
border-right-style: solid;
border-left-style:double;
border-bottom-style:solid;
For combining all properties:
border: 3px solid red;
Padding:
padding:300px 100px
padding-left:350px
Radius:
border-radius:350px;
border-top-left:350px;
div:hover
background-color:blue;
border:5px double yellow;
transform:skew(30deg);
transition: transform 3s;
transform – scale, skew (in deg), rotate(in deg)
Refer for all transformation related code
div
margin: 100% 50% 100% 50%;
border-width:5px;
border-color:black;
border-top-style: dotted;
border-right-style: solid;
border-left-style:solid;
border-bottom-style:dotted;
padding-right:100px;
padding-left:100px;
border-top-left-radius:100px;
border-top-right-radius:100px;
border-bottom-left-radius:100px;
border-bottom-right-radius:100px;
animation:myfirst 5s;
}
div:hover
background-color:pink;
border:5px double green;
transform:scale(1.3) rotate(360deg);
transition: transform 5s;
box-shadow:rgb(0,100
,0) 20px 20px;
@-webkit-keyframes myfirst
from{background:pink;border:5px}
to{background:yellow;border:3px solid black}
To create an animation
animation:myframe 5s
@webkit-keyframe 5s
}
HTML -5
Drawbacks of HTML4
No support for audio/video
Only supports few input tags (email, search, date, time etc.)
No validation support (required, range, pattern)
Few schematic elements (like <p> <div>). HTML-5 has more
schematic elements (like header, footer, article, section, aside)
No canvas support (no drawing support). HTML-5 has <canvas>
</canvas> (we can draw inside this tag)
Not mobile friendly
No offline support. HTML-5 has localstorage and sessionstorage
(to store data offline)
Only few form attributes. HTML-5 has new attributes for forms
Basics of HTML
HTML5 will be the new standards for developing web pages
Created by WHATWG and W3C
WHATWG (web hypertext application technology working group) is
combination of companies who owns browsers
New feature of HTML5:
New content specific tags (article, footer, header)
New form controls
The canvas element for drawing
Audio video support
Schematic Elements:
<html>
<head>
<title></title>
</head>
<body>
<header>
</header>
<nav></nav>
<article></article>
<footer></footer>
<body>
</html>
Details and figure element:
New Input type:
Email
url
Number
Range
Date picker (date, month, week, time, datetime, datetime-local)
search
color
Canvas (to draw shapes):
CSS for different devices
<html>
<style>
.c1{
background-color:cadetblue;
color: black;
</style>
<style media="screen and (min-width:700px)">
.c1{
background-color: brown;
color:burlywood
</style>
<body>
<div class="c1">Testing Media...</div>
</body>
</html>
Z-index
Position absolute and relative
display-flex
Bootstrap 5
Bootstrap is a file with .css extension with its own property and values.
It is a free front-end framework for faster and easier web development.
It allows us to create responsive designs.
It includes html and css based design templates for typography, forms,
buttons, tables, navigation, model(dialogue box),image
carousels(scrolling image) and many others, as well as optional
Javascript plugins.
Mark otto and Jacob Thornton developed Bootstrap.
Bootstrap 3 & 4 r using Jquery now bootstrap 5 using javascript.
Advantages
1.Easy to use
2.Responsive behaviour
3.Mobile first approach
4.Browser compatibility
Two ways of start using Bootstrap
1.Bootstrap from CDN(Content delivery network)
2.Download bootstrap using npm command(node package manager)
>Create layout first-always use container
SYNATX: <body class="container">
We use container for applying padding
1.The .container class provides a responsive fixed width container.
2.The .container-fluid class provides a full width container,spanning the
entire width of the viewpoint.
BOOTSTRAP GRID SYSTEM : Using grid system v can adjust the page
content based upon the devices.
Grid system is a combination of rows and columns(12 columns AND *ROWS)
syntax: <div class="row">
<div>first</div>
</div>
max-width
1.extra-small = <576px
2.only small = >576px
3.medium = >768px
4.large = >992px
5.extra large= = >1200px
6.xxl = >1400px
Grid system has six classes:
1.col-xs(extra small devices)
2.col-sm-(small devices)
3.col-md-(medium devices)
4.col-lg-(larger devices)
5.col-xl-(extra large device)
6.col-xxl- above 1400px
TYPOGRAPHIC CLASSES
1).lead-makes paragraph stand out
2).text-start-indicates left-aligned text
3).text-break-prevents long text from breaking layout
4).text-center-indicates center aligned text
5).text-decoration-none- removes the underline from a link
6).text-end-indicates right-aligned text
7).text-nowrap-indicates no wrap text
8).text-lowercase-indicates lowercase text
9).text-uppercase-indicates uppercase text
10).text-capitalize-indicates capitalized text
.TEXT-PRIMARY
COLORS CLASSES
1.PRIMARY - Dark blue[used to highlight/something important like heading]
2.SECONDARY - Subheadings
3.SUCCESS - Green[user created successfully]
4.WARNING - Orange yellow[displaying error message]
5.DANGER - Red[stock goes below min level]
6.MUTED - Grey[disable the button/text box]
7.INFO - Light blue[to display product description]
8.btn dark-black
TABLES CLASSESS
1].table-primary - blue
2].table-light - light grey table or table row background
3].table-dark - dark blue
all the color classes can be used with table classes
IMAGES SHAPES
1]Rounded corners -.ROUNDED-CIRCLE
2]Circle
3]Thumbnail-img-thumbail
PADDING-pt same as margin
MARGIN-mt-top,mb-bottom,ms-left,me-right,mx-*-left and *-right,my-top and
bottom,blank-all 4 sides
Padding and Margin Sizes - 1 to 5 (measured in rem)
1 rem = 16px
Class value Size(in rem) Approx Size(in px)
0 0 rem 0px
1 0.25 4px
2 0.50 8px
3 0.75 12px
4 1 16px
5 1.25 20px
Navigation bar:
Classes in Bootstrap to create navigation bar:
nav
navbar
navlink
navitem
nav-brand
navbar – acts as a container to create navigation bar. It will apply necessary
padding and margin. All bootstrap classes will be inside navbar class
nav- it will remove bullets. Aligns all content horizontally.
nav-brand- aligns the brand to the left position and remaining content to the
right position automatically.
nav-link - removes underline. Applies padding and margin to the navbar
<ul></ul> tags are used.
Eg:
<head>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.cs
s" rel="stylesheet" integrity="sha384-
SgOJa3DmI69IUzQ2PVdRZhwQ+dy64/BUtbMJw1MZ8t5HZApcHrRKUc4W0kG8
79m7" crossorigin="anonymous">”
<body>
<header></header>
<nav>
<ul>
<li><a href “#”>Home<a></li>
<li><a href “#”>Forms<a></li>
<li><a href “#”>Cards<a></li>
<li><a href “#”>Navtabs<a></li>
</ul>
</nav>
Form controls
Textbox – form-control
Button:
o btn btn-success, primary, warning, danger, muted.
o Buttons come in three sizes (large [btn-lg], default, small [btn-
sm]).
o To show only the outline of the button [class = “btn btn-outine-
success”].
o Button active/disactive: [<button type= “button” class=”btn btn-
primary active”> Active button <button>
o To group the buttons [class =”btn-group”]. To group the
vertically [class =”btn-group-vertical”].
Checkbox, Radio- form-select
nav tabs/ navpills
Classes used for nav tabs:
o nav-tabs – creates nav container along with tab button
o nav-items – sets the padding and margin
o nav-link – add bootstrap hyperlink (removes underline)
o tab-content – container to display the content
o tab-pane – creates sections of content
Classes used for nav pills:
o nav-pills
o nav-items
o nav-link
o tab-content
o tab-pane
To switch the page dynamically: [data-bs-toggle]
To make the content blink for a sec: [tab-pane fade]
Eg:
<h1>Nav Tabs</h1>
<ul class="nav nav-tabs" id="nav-pills">
<li class="nav-item">
<a class="nav-link active" id="pill1-tab" data-bs-toggle="tab"
href="#p1" >Tab 1</a>
</li>
<li class="nav-item">
<a class="nav-link" id="pill2-tab" data-bs-toggle="tab"
href="#p2">Tab 2</a>
</li>
<li class="nav-item">
<a class="nav-link" id="pill3-tab" data-bs-toggle="tab" href="#p3"
>Tab 3</a>
</li>
</ul>
<div class="tab-content mt-3" id="nav-pills-tabContent">
<div class="tab-pane fade show active" id="p1">
<p>Content for Tab 1</p>
</div>
<div class="tab-pane fade" id="p2" role="tabpanel">
<p>Content for Tab 2</p>
</div>
<div class="tab-pane fade" id="p3" role="tabpanel">
<p>Content for Tab 3</p>
</div>
</div>
<h1> Nav Pills</h1>
<ul class="nav nav-pills" id="nav-pills">
<li class="nav-item">
<a class="nav-link active" id="pill4-tab" data-bs-toggle="tab"
href="#p4" >Tab 1</a>
</li>
<li class="nav-item">
<a class="nav-link" id="pill5-tab" data-bs-toggle="tab"
href="#p5">Tab 2</a>
</li>
<li class="nav-item">
<a class="nav-link" id="pill6-tab" data-bs-toggle="tab"
href="#p6" >Tab 3</a>
</li>
</ul>
<div class="tab-content mt-3" id="nav-pills-tabContent">
<div class="tab-pane fade show active" id="p4">
<p>Content for Tab 1</p>
</div>
<div class="tab-pane fade" id="p5" role="tabpanel">
<p>Content for Tab 2</p>
</div>
<div class="tab-pane fade" id="p6" role="tabpanel">
<p>Content for Tab 3</p>
</div>
</div>
Cards
Classes used for cards:
card
card-header
card-body
card-title
card-text
card-footer
Eg:
<article>
<div class="card">
<div class="card-header"></div>
<div class="card-body">
<p class="card-title"><h1>Student Details</h1></p>
<p class="card-text"> Name: Dharshini <br> Age:21 <br> Address:
Chennai </p>
</div>
<div class="card-footer"></div>
</div>
</article>
Toast
Toast is a small window which is meant to display notifications for the user
Classes used for toast:
toast – a class that creates a small window
toast-header – meant to display the title
toast-body - meant to display the content
Eg:
<div class="toast-container position-fixed bottom-0 end-0 p-3">
<div id="liveToast" class="toast">
<div class="toast-header">
<strong class="me-auto">Bootstrap</strong>
<small>Just now</small>
<button type="button" class="btn-close" data-bs-dismiss="toast"
></button>
</div>
<div class="toast-body">
Hello! This is a Bootstrap toast notification.
</div>
</div>
</div>
<button type="button" class="btn btn-primary"
id="showToastBtn">Show Toast</button>
<script>
document.getElementById('showToastBtn').addEventListener('click',
function () {
var toastEl = new
bootstrap.Toast(document.getElementById('liveToast'));
toastEl.show();
});
</script>
Panels
Carousel
Classes used for carousel:
carousel – an area where image will be displayed. Container for images
carousel-inner – next and previous button displays inside the carousel
carousel-item – contains the content to be displayed in the carousel
carousel-control-prev – converts button to corresponding arrow
data-bs-slide – switches the images dynamically. Without this class the
content is static
carousel-control-next - converts button to corresponding arrow
Eg:
<div id="carouselExample" class="carousel fade-in">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="bk.jfif" alt="Slide 1">
</div>
<div class="carousel-item">
<img src="banner.jfif" alt="Slide 2">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-
target="#carouselExample" data-bs-slide="prev">
<span class="carousel-control-prev-icon"></span>
</button>
<button class="carousel-control-next" type="button" data-bs-
target="#carouselExample" data-bs-slide="next">
<span class="carousel-control-next-icon"></span>
</button>
</div>
To covert the button to close icon [class="btn-close"]
To close the toast window [data-bs-dismiss="toast"]
Breadcrumbs
Displays the complete path of the current page ie. parent page to child page
Classes used in breadcrumbs:
breadcrumb – create a breadcrumb bar with basic padding and margin
breadcrumbitem- display the page hyperlink
Pagging
JavaScript
Javascript was introduced for validation purpose.
Javascript can be used for backend.
Javascript helps to make the content dynamic.
Introduction to Javascript:
Javascript was initially known as live script
Javascript was initially made to validate HTML page
Javascript is a client-side scripting language
Javascript can run on any operating systems
Purpose of Javascript:
Change the browser settings (disable the features of the page say for
disabling right click)
Create DHTML pages css + html + javascript
Create dynamic windows to display ads
Detects browser
Javascript in an HTML page:
Start by using script tag
The internet browse will read both the HTML and Javascript syntax and
process the page accordingly.
Where to put the Javascript:
Javascript are executed when
A webpage loads into the browser
When an event is triggered
How to start with Javascript:
Syntax: <script>
-----content-----
</script>
Scripts in body and head section:
<html>
<head>
<script>
------content-----
</script>
</head>
<body>
<script>
-----content----
</script>
</body>
</html>
External CSS – put <script> in head block
Internal CSS - put <script> in body block
Structure of Javascript:
<script type = “text/statement”>
document.write(“Welcome to JS”)
</script>
Javascript and DOM:
DOM – Document Object Model
A document has many elements(object), Javascript uses some methods
to access those elements and modify them using some methods. This
is pretty much what DOM is.
It organizes the entire html document in a tree structure
Document object properties: properties will always take an equal to
bgcolor – set background color. [document.bgcolor = “red”]
fgcolor – set color for attributr of <body> tag.
[document.fgcolor=”yellow”]
linkColor – specify the color of the hyperlink. [document.linkColor =
“green”]
title – used to set the title of the document. [document.title =
“title”]
Document object methods:
write() – used to print content on the webpage
getElementById – used to retrieve element with specific id
getElemenrByTagName - used to retrieve an array of all elements
having a specific tag name. Eg: var c =
document.getElementByTagName(“img”)
c.src=”a.jpeg;”
datatype
int x = 100 value
variable name
In javascript the datatypes are replaced with var
var x = 100
Variant
Variables:
Information is stored in variable
Its value can be changed during the execution of script
Datatype – Variant
Variant can store any datatype
Declaring Variables:
Implicit declaration
Explicit declaration
Implicit declaration:
Declare variables by using its name directly in the script
Eg: name=”tom”
Explicit declaration:
Declare variable by using var keyword
Eg: var name
name=”Tom”
Rules for variable names:
Must begin with letter
Cannot contain a period
Cannot exceed 255 characters
One variable cannot store multiple values
Operators:
Arithmetic -, +, *, /, %
Logical - &&, ||, !
Relational - < , > , =, <=
Conditional Statements:
if
if-else
nested-if
Conditional Statement – if:
if(count==5)
document.write(“five”)
Conditional Statement – if-else:
if(count==5)
document.write(“five”)
else
(a=a+1)
}
Conditional Statement – nested-if:
if(count==5)
document.write(“five”)
elseif
(a=a+1)
else
b=b+1;
Conditional Statement – switch:
var loc = “Bamg1”
switch(loc)
{
Javascript Loops:
for – loops through a block of code a specified number of times
while – loops through a block of code while a specified condition is true
do while – will always execute once and repeat it until the condition is
true
For loop:
Syntax:
for(var=startvalue; var<=endvalue; var=var+increment/decrement)
Note: to use any HTML code into Javascript use it like
[document.write(“<tag>”)].
Eg: [document.write(“<br>”)]
While loop:
Syntax:
while (condition) {
code to be executed
Do while loop:
Syntax:
do
code to be executed
while(var<=endvalue);
Javascript – Popup Boxes
Three Popup boxes in Javascript:
Alert – has one button
Eg: alert (“Beware of fraud”)
Confirm – always has two buttons. These buttons have a value.
Eg: if (confirm(“Are you awake?”) == 1)
document.write(“Good for you”);
else
document.write(“Bad for you”);
Prompt – accept a value from the user before opening the page.
Eg: var name = prompt(“Enter your name”)
Declare Variables:
var - global scope
Can declare multiple times. Can be accessed outside the local scope
let – local scope
Can declare only once. Cannot be accessed outside the local scope
const
redeclaration is not possible
Function:
Create a function:
function function_name()
Call a function:
function_name();
parseint – converts string to integer
parsefloat – converts string to float
Event Handlers:
onblur – when the text box loses focus onblur is called
onfocus – when the text box is on focus onfocus is called
onclick
onchange
onkeypress
onload
onmousemove
onmouseout
onmouseover
onreset
onselect
onsubmit
onunload
Functions:
String:
console.log(str.length); - to know the length of the string - length is a
property(
console.log(str.toUpperCase()); - to change the string into uppercase
console.log(str.toLowerCase()); - to change the string into lowercase
console.log(str.includes(“Word”)); - to check whether the part is
present in the string
console.log(str.startsWith(“Word”)); - to check whether the string
starts with the word
console.log(str.endsWith(“Word”)); - to check whether the string ends
with the word
console.log(str.substring(0,5)); - To print that particular part of that
string
console.log(str.slice(-7)); - if (-7) 6 characters will be removed
let newStr = str.replace(“World”, “Javascript”);
console.log(newStr); - replace one word with other in the string
let messy = “ trim me “;
console.log(messy.trim())
split()
concat() – let a = “Hello”;
let b = “JS”;console.log(a.concat(b));
Date:
Date is a built-in function
syntax: object name = new class name();
Full year – getFullYear();
Month – getMonth(); - starts with 0 index where 3 – April
Date – getDate();
toDate – today.toDateString(); - current date
toTime – today.toTimeString(); - current time
Custom format:
let formatted = ‘ ${d.getDate()}/ ${d.getMonth() + 1} / $
{d.getFullYear()}’
console.log(formatted);
Number:
INT - console.log(parseInt(“123”)) ;- convert string to integer
FLOAT – console.log(parseFloat(“12.34”)); - convert string to float
Not a Number – console.log(isNaN(“abc”)); - checks if the string is a
number
Finite - console.log(isFinite(123));
Round - console.log(Math.round(4.5)); - gives the nearest round number
Ceil - console.log(Math.ceil(4.1)) – returns 5
Floor - console.log(Math.floor(4.9) – doesn’t count the point value
Max - console.log(Math.Max(10, 25, 40)) – returns the larger number
Min - console.log(Math.Min(10, 25, 40)) – returns the smaller number
Arrays:
Array is a collection of variables having similar datatype.
Create an array:
1. Array class
Syntax: arrayname = new Array();
var a = new Array();
2. Using array keyword
Syntax: var arrayname = []
For each loop:
Requires no indexes
Only used to read all values
refer programs - array.html, array.js [Path –> Documents – Javascript]
Working with objects:
Objects are a combination of properties and methods
Properties:
Eg:Properties always expects data from the user
bgcolor, fgclor, title, linkcolor
Methods:
Performs the action
Eg:write, writeln, getElementbyId
How to create custom object?
Three ways to create an object:
Using object keyword
Using arrays
Using constructor function
Using object keyword:
var ob = new Object();
It creates new object by the name ob.
var ob = new Object()
studentid: 100,
studentname: ‘Raj’,
class:10
};
refer programs - OOPDemo.html, oop.js [Path –> Documents –
Javascript]
Using arrays:
var ob ={
properties
empid:23450
emp:Jay
methods
Using constructor function:
Use constructor function when you want to work with multiple objects, with
different data.
Syntax:
function Person(sid, sname, totalmarks)
//properties this.studentid = sid; // “this” is a global variable
this.studentname = sname;
this.totalmarks = totalmarks;
//methods this.show = fuction({
alert(this.studentid)
alert(this.studentname)
})
var ob = new Student(100, ‘ajay’, 34);
Functions
Instance function: called via objects. Will have logic which is not common
to objects
this.hello = function()
Static Function: Will have logic common to all objects
Person.prototypr.hello = function
Advantage: Reduction in memory usage
Anonymous function: let a = function() {return “Hello”}
Typescript
Drawbacks of Javascript:
Limited features – no support for datatypes, has no generics, has no
access specifiers
No compile time checks
Not truly OOP
Typescript features:
Class
Types
Interfaces
Generics
Datatypes
Variables:
Variables are container to hold data and is done by var keyword let
keyword
If we skip keyword to declare a variable, we get an error message as
“cannot find name”
Types:
Type is a classification of data which tells the compiler or interpreter
how the programmer intends to use the data.
Javascript is weakly typed language, and Typescript is strongly typed
language.
Datatypes:
Number
String
Boolean
Array
Enum
Void and Any
Datatype Usage
Number Var age:Number
A=10
String Var PAN: string,
a =”abcd123”
Boolean Var IsIndian: Boolean
IsIndian = true
Any Var caddress:any
A=10
A=”India”
Array A:datatype=value
A:number[]=[1,2,3,4]
How Typescript works?
Create Typescript file with .ts extension
Compile: tsc.ts // here the file is actually transfilling not compiling
(converting to one language to other)
Generated output
function hi(a:number)
console.log("You have entered"+a);
function add(a:number, b:number): string
{
let res:number = a+b;
return `The sum is ${res}`
let str = add(10,20)
console.log(str);
function custdetails(): [number, string, boolean]
let custid: number =100
let custname: string = 'Dharshu'
let isindian: boolean =false;
return[custid,custname,isindian]
var [a,b,c] = custdetails()
console.log(custdetails())
function myarray(): number[]
return [1,2,3,4,5]
const number = myarray()
number.forEach(e=> {
console.log(e)
});
Create a class and call a function
class myclass{
public hello() //public-access modifier
console.log("Call the Function")
let ob = new myclass()
ob.hello()
You can call a function by creating an objects
Inheriting a class:
class myclass{
constructor(){
console.log("Constructor Called")
public hello() //public-access modifier
console.log("Call the Function")
class myclass2 extends myclass{
}
let ob = new myclass()
ob.hello()
To compile all ts file:
To compile all the files in one go, use – tsc*.ts
To store the JS and TS files separately, use - .tsc src/*.ts
src folder stores all the ts files
dist folder stores all the js files
Complie entire project with tsconfig.json:
To create tsconfig.json
tsc –init
Tuples – to use more than one datatype in a function
Enum – to specify the function to take only a specified type of values
enum Direction{
Up,
Down,
Left,
Right
let move: Direction = Direction.left;
void: specifying does not allow to a return value
fuction f1(): void
Special types representing “no value”
null – intentional absence of value
email: string: null
undefined – variable declared but not as signed
email:string
Type Inference:
Typescript understands what datatype of the element is without specifying it.
let county = “India” // India is inferred as string
Type casting:
Changing one datatype to other. Happens at runtime
a : num = 100
(string)a
Type assertion:
Used to tell the compiler the specific type of variable. Happens at compile
time
let value: any =”hello”;
let length = (value as string).length;
Const Declaration:
Never change the value
Inheritance of classes:
Use “extends” keyword to inherit one class to other
Generic:
swap<T> (a:T, b:T)
Session storage:
sessionStorage.setItem(key, value)
Angular
Module 1 - Introduction to Angular:
All communication from the server side to Angular happens in JSON format
Difference between Angular JS and Angular:
Features Angular JS Angular
Release date 2010 2015
Language Uses Javascript Uses Typescript
Architecture MVC – Model view MVC + Component
based
Tooling Support No support Does support
Mobile Support No support Does support
Performance Low performance High performance
Community Support Less support Wide support
Difference between Angular and Javascript:
Javascript Angular
Limited Features Supports datatypes, OOP features
No compile time support Compile time support
No built-in libraries Supports built-in libraries for forms,
validation, styles, security, backend
communication
Difficult to test Easy testing
What is Angular?
Angular is javascript framework for creating single page web
applications (SPA)
Developed by Misko Hevenry and Adam Abrons and managed by
google.
Angular provides developers options to write client-side application in a
clean MVC architecture.
It is a binding framework – working with data(data features).
Benefits of SPA:
No page refresh
Better user experience
Ability to work offline
Features of Angular:
MVC Patterns
Directives – extend HTML
Two-way Data Binding
Filters
Typescript support
Easy Testing
SPA made simple
MVC – Model View Controller:
Model contains TS files. The main purpose of the model is to interact
with web API in the server. The web API converts data into JSON
format.
View contains all the UI files (HTML, CSS, Bootstrap). View cannot
interact with model directly.
Controller/Component contains many TS files. The job of the
controller/component is to interact with the model.
Directives – extended HTML:
Directives are custom tags (created by the user).
Custom attributes are directives too.
Purpose of directives is to show data in the right format.
Two-way binding:
The two-way are view and controller. Any change in one element will update
the other. The change is updated in all the areas.
Filters:
Angular JS used filters. In Angular filter are replaced as pipes.
Filters allows to change the format of the content without changing its
meaning
Some types of filters/pipes:
Date filter
Currency filter
Uppercase filter
Custom range filter
Setting the environment:
npm – node package manager must be supported
node v – verify the version
npm install -g @angular/cli – to install angular
ng version – check the version of angular
To create angular project – ng new projectname --routing --no-standalone
Website name will be projectname
node_modules – this folder contains all the packages
src – it contains all the user created files inside app folder. Images, audio,
video are stored in assets folder.
ng serve – this command launches the server, watches your file and
rebuilds the app as you make changes to those files. compile + run
ng build – only compile
How to create a component:
Component = Four Files:
.html
.css
.ts
.spec.ts – used for testing
Angular component file: app.compnent.ts
file name
import { Component } from '@angular/core'; - package
class name
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
standalone: false,
styleUrl: './app.component.css'
})
export class AppComponent creates
variables/function/classes
title = 'onlineshop';
}
{{}} – interpolation – a way to incorporate any html or css or js element
Property binding – the value for attribute is retrieved from .ts file
a:string = “link”
<html>
<body>
<a [href] = “a”>Click Here </a>
Binding: It is a process in which variables are mapped to html elements for
data attributes. Different types of binding are:
Interpolation - {{}}
Property Binding - []
Event Binding - () - click, change
Class Binding : its similar to property binding. It’s a variable mapped to
class attributes.
Style Binding
Two types of Binding:
Static Binding
Dynamic Binding - the values are retrieved from .ts file.
<!-- static binding -->
<div class="first">Hello Universe</div>
<br>
<!-- dynamic binding -->
export class AppComponent {
mycls: string = "first"
<div [class]="mycls">Hello Universe</div>
<!-- conditional class -->
<div [class.first]="b">Hello Universe</div>
For all reference
HTML File:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Angular</title>
<style>
.first{
color: turquoise;
background-color: black;
}
.second{
border: 3px solid blue;
}
</style>
</head>
<body>
<h1>Welcome to Angular</h1>
<hr>
<p>{{name}} </p>
<br>
<!-- static binding -->
<div class="first">Hello Universe</div>
<br>
<!-- dynamic binding -->
<div [class]="mycls">Hello Universe</div>
<br>
<!-- conditional class -->
<div [class.first]="b">Hello Universe</div>
<br>
<!-- multiple classes -->
<div [class] = "myclassfunc()">
Angular Rocks!!!!!!!!!!!
</div>
<br>
<!-- simple style -->
<div style="background-color: brown;">Good Morning</div>
<br>
<div [style] ='s'>Hello Morning</div>
<br>
<div [style] = "stylefunc()">Hello Earth</div>
<br>
<div class="bg bg-primary">
<label>Name: </label>{{Name}} <br>
<label>Age: </label>{{age}} <br>
<label>Nationality: </label>{{IsIndian}} <br>
<label>Address: </label>{{Address}} </div> <br>
<div>{{display()}}</div><br>
add: {{2+2}}
<br>
<a href="https://www.google.co.in/">Click here</a> <br>
<a href={{url1}}>Click Me</a> <br>
<a [href] = "url2">Shop</a> <br>
<img src="{{img}}" width="300"/> <br> <br>
<img
src="https://tse3.mm.bing.net/th/id/OIP.9MuIkTTF4KQa1pqZK48DyQHaEo?
rs=1&pid=ImgDetMain" width="300"/> <br>
<input type="number" id="b1" /> <br>
<input type="number" id="b2" /> <br>
<input type="button" id="b3" (click)="addnums()" /> <br>
{{result}} <br>
<input type="text" id="d1" value=""/> <br>
<input type="text" id="d2" value=""/> <br>
<input type="text" id="d3" value=""/> <br>
<input type="button" (click)="simpleinterest()" /> <br>
{{result1}} <br>
<form (submit)="registerform($event)">
<label for="t1">Name:</label>
<input type="text" id="t1" placeholder="Enter name">
<br>
<label for="t2">Enter DOB:</label>
<input type="date" id="t2" placeholder="Enter DOB">
<br>
<label for="t3">Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female
<br>
<label for="t4">Email:</label>
<input type="email" id="t4">
<br>
<label for="t5">Nationality</label>
<select id="t5">
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="China">China</option>
</select>
<br>
<input type="submit" value="Submit">
</form>
<ul>
<li>Name: {{ name }}</li>
<li>DOB: {{ date }}</li>
<li>Gender: {{ gender }}</li>
<li>Email: {{ email }}</li>
<li>Nationality: {{ nationality }}</li>
</ul>
<br><br>
</body>
</html>
CSS File
h1{
background-color:bisque;
text-align: center;
color:brown;
}
p{
color:red;
background-color: black;
}
div{
color: black;
background-color: blanchedalmond
;
}
TS file
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
standalone: false,
styleUrl: './app.component.css'
})
export class AppComponent {
mycls: string = "first"
b: boolean = false
s: string = "background-color: red"
stylefunc(){
var res ={
"background-color": "red",
color: "yellow",
border: "3px dotted blue"
}
return res
}
title = 'onlineshop';
name:string = "Mphasis ltd..."
Name: String = 'Dharshu'
age:number = 21
IsIndian: boolean = true;
Address: any = '336, 8th cross street, BEML Layout'
url1: string = "https://www.google.co.in/"
url2: string = "https://www.myntra.com/"
img: any = "assets/img.jpg"
display()
{
return "Hello World"
}
myclassfunc(){
let res ={
first: true,
second: true
}
return res
}
result: number =0;
addnums(){
let a = (document.getElementById("b1") as HTMLInputElement).value
let b = (document.getElementById("b2") as HTMLInputElement).value
this.result = parseInt(a) + parseInt(b)
}
result1: Number =0;
simpleinterest()
{
let a =(document.getElementById("d1") as HTMLInputElement).value
let b =(document.getElementById("d2") as HTMLInputElement).value
let c =(document.getElementById("d3") as HTMLInputElement).value
let principle=Number(a);
let rate=Number(b);
let time=Number(c);
this.result1 = ((principle*rate*time)/100);
}
dname='';
date='';
gender='';
email='';
nationality = '';
registerform(event: Event) {
event.preventDefault();
this.name = (document.getElementById("t1") as HTMLInputElement).value;
this.date = (document.getElementById("t2") as HTMLInputElement).value;
const selectedGender =
document.querySelector('input[name="gender"]:checked') as
HTMLInputElement;
this.gender = selectedGender ? selectedGender.value : '';
this.email = (document.getElementById("t4") as HTMLInputElement).value;
this.nationality = (document.getElementById("t5") as
HTMLSelectElement).value;
}
}
Create new files into project – npx ng g c filename
To run both the html and css page together – npx n g c testing -t -s
inline
Router out acts as placeholder to display the component based on the
current url
<router-outlet></router-outlet>
HREF: reloads the browser
routerLink: Updates the part of the page
Structural directives: (these are used in the HTML page)
if - *ngIf
for - *ngFor
switch - *Switch
To display in the list format:
<div *ngFor =”let item of array”></div>
<ul *ngFor=”let item of array”>
<li>{{item}}</li>
To display in the table format:
<table>
<tr *ngFor = “let item of array: let i = index>
<td>{{item}}</td
<tr>
</table>
Keywords for “For” loop:
index – position of the current element
first – true if current item is the first item
last - true if current item is the last item
even - true if current item is in the odd position
odd - true if current item is in the even position
Command to create component – ng g c component name
Command to create inline component – ng g c component name -t -s
Difference between template and templateurl:
template:<h1>hello</h1> - directly takes a HTML element
templateurl: “app.html” = take an external file
The files created are:
angular.json - applying settings for the entire project
Eg: applying css: style
applying js: script
project folder: configure assets folder
This file decides which file to load when we run ng serve command.
component à app.ts à app.module.ts à main.ts à angular compiler
package.json – contains all the packages which is required to run the
application
It contains:
version number
settings on how to test and run angular project
tsconfig.json - it contains
information about typescript version
compiler to be used
where the output file needs to be created
app.module.ts – a file where we register all user defined components.
We register in declaration sections
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
ProductsComponent,
RegisterComponent,
ContactComponent,
BuyComponent,
PagenotfoundComponent
],
To define a user-define component(components of module):
declaration: register here
import: register built-in class here
provider: register external file
bootstrap: if you need to use component in index.html file, then
register here.
app.routing.ts – used for navigation support
{path: “abc” , component:login}
Child components:
A child component is a component that exists within a component. The
reusable logic goes here.
How to create child component:
Step 1: Create component – npx ng g c filename
1.@Component({
Selector:”my-child”,
Template:”this is a child component
})
Export class AppComponent{}
Step 2:In routing.ts register the parent
Step 3:Call the child in parent through <app-child></app-child>
Step 4:Add child selector to the markup
How to send data between parent to child:
Use input keyword – if we want to send data between parent to child
Use output keyword – If we want to send data between child to parent
Child to parent communication happens only using events:
Step1:parent.component.ts
// reverse data comes from child tp parent
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
standalone: false,
templateUrl: './parent.component.html',
styleUrl: './parent.component.css'
})
export class ParentComponent {
a:string ="Hello"
data:string="";
display(p:string){
this.data=p;
}
}
Step2:parent.component.html
<p>parent works!</p>
<app-child [message] = "a"></app-child>
<hr>
<app-child (myevent) = "display($event)"></app-child>
<div>Message from child is {{data}} </div>
Step3:child.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-child',
standalone: false,
templateUrl: './child.component.html',
styleUrl: './child.component.css'
})
export class ChildComponent {
@ Input() message:string='';
@ Output() //code to create custom event
myevent: EventEmitter<string> = new EventEmitter<string>;
executefunc()
{
//code to run the event
this.myevent.emit('Angular Kills')
}
}
Step4:child.component.html
<p>child works!</p>
<div>
Data from child- {{message}}
</div>
<hr>
<button (click) = "executefunc()">Click</button>
What is ng-content?
<ng-content> is angular’s way of projecting content from a parent
component into a child component. It’s like putting placeholder in a child
component where the parent can be inserted.
What is ViewChild?
You want to access an element, directive, or component that’s declared in
your component’s own template.
@viewchild(“d1”) st!: elementref
function display()
st. nativeelemnet.innertext = ‘helloworld’
st.nativeelement.style.color=’yellow’
//logic to change color
}
<button click = “display()”>
<div #d1>
change some settings here
<div>
What is ContentChild?
You’re writing a reusable component that accepts content from the outside,
and you want to access that projected content.
@ContentChild(‘message’) messageRef! ElementRef;
Angular Lifecycle hooks:
Angular lifecycle hooks are special methods that Angular calls automatically
at specific points in a component’s life cycle.
Methods:
1. ngOnChange This method gets called when every
time input value changes
2. ngOnInit When the component is initialized.
Will be called when the entire
component is ready to use it
3. ngDoCheck Called every time there is a change
in the view page
4. ngAfterContentInit This method gets called when page
content is initialized
5. ngAfterContentChecked This method is called when page
content is updated
8. ngOnDestroy Called when component is
destroyed (unload)
6. ngAfterViewInit This method is called when view is
fully initialized (loaded)
7. ngAfterViewChecked This method is called when view is
updated.
ngOnInit(){
//called only one in lifetime.
//Best for initialization of global variable, connection to database
console.log('Init function called')
}
ngDoCheck(){
//never write any long code here, esle you'll face performance issue
console.log("Do check method called")
//write code only to monitor all the changes happening in the
component
}
test1(){
alert("Welcome")
}
test2(){
alert("Not Welcomed")
}
}
Angulars and dependency injections:
Angular service is a class that contains reusable business logic, data access
or utility functions which can be shared across multiple components.
Services are used to create logic and use it multiple times.
Services help keep your components lean and focused on the UI by moving
logic (like fetching data from an API) into a separate class.
How to create a service?
It is created in three steps:
(Build)Create a service
Register a service
(Inject)Use the service
Building a service:
export class MathService{
add(){
//add logic
ng g service MathService (create a service)
Register the service(it is automatic):
It can be registered in the app.module.ts or in the app.component.ts
In the app.component.ts
providers:[MathServies]
Use(injection) the service:
Two methods to use the service:
Singleton – one object is created for multiple clients. This the default. (like
booking a bus ticket). Use Injector and provider
Non – Singleton - each client has a separate object (like adding to cart).
When the provider is added in the component directive, an object is created,
and it becomes non-singleton.
Call the services:
constructor (private ob: MathService){}
Dependency Injections:
A coding pattern in which a class receives the instances of object it needs
(called dependencies) from an external source rather than creating them
itself.
Create a service file:
npx ng g service Math(filename)
In home.component.ts
import { MathService } from '../math.service';
In math.service.ts
export class MathService {
addnums(a:number, b:number):string{
let c=a+b
return "The sum is="+c
}
In home.compnents.ts
{{result}}
Injectable – client will not create the object, it will create the object
@Injectable() – marks the class as DI
provideln: ‘root’ – it makes singleton
Debugging and Error Handling:
Types of errors:
Syntax
Runtime – can be fixed using try block and catch block
Logical – can be fixed by using debugging
Angular dev tools:
Downloaded as an extension from google and allow real time changes in the
browser.
Try and Catch
divnums(a:number, b:number):any{
try{
let c=a/b;
if(b==0){
throw new Error("You are trying to divide by 0")
}
return "The quotient is="+c
}
catch(Error){
console.log("Error occured"+Error)
}
}
Global error handle:
Create a service file
create the method called ErrorHandler
create handleError
Reference:
import { ErrorHandler, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GlobalerrorService implements ErrorHandler{
handleError(error: any): void {
console.log("Globally Error is handled")
console.log(error)
}
constructor() { }
}
Forms Programming:
Angular form is used to collect, manage, validate and submit user input in a
structured way.
Two types of forms:
Template Driven Form - HTML
Model Driven Form – TS
Template Driven Form:
Template refers to HTML page
A template driven form in Angular is a type of form where most of the logic
defined in the HTML template rather than in the component class.
It relies on Angular directives like NgForm and NgModel to manage form
controls and validation.
Template: (in the HTML File)
Input Elements
Data Binding
Validation
Error Message
Model Driven Form:
Model refers to component class
A model driven form in Angular also known as a reactive form is a type of
form where the form structure and validation are defined in the component
class rather than in the template. It provides more control and flexibility
compared to template driven forms.
It uses the FormGroup and FormContol
Form validation is handled programmatically.
FormGroup and FormControl are directive
export class ContactComponent {
f: any
constructor(){
this.f = new FormGroup({
username: new FormControl("admin",
[Validators.required,Validators.pattern("[a-z")]),
email: new FormControl("admin", [Validators.required]),
msg: new FormControl("admin", [Validators.required,
Validators.maxLength(10)]),
})
}
}
Template: (in the Component File)
Validation
Data Binding
Error message
Template Driven Model Driven
Simple Code Complex code
Used for simple scenario More advance scenario
Supports two-way binding No two-way binding
Not suitable for large applications Suitable for larger application
Uses HTML attributes for Form Uses classes for Form Validation
Validation
Template Driven Forms:
<form #editForm = “ngForm” (ngSubmit) = “logForm(editForm)”>
</form>
#edit – variable
ngForm: is a Form Instance that provides a way to track the value, state
and validity of the form and all its controls(like input field, checkboxes).
ngForm will read all the input textbox and dump the value to variable
#frm = ngForm
ngModel: ngModel directives registers the field with the ngForm
#u=ngForm
ngForm and ngModel are used in combination
Eg:
<div style=" width:500px; margin-left: 500px;">
<form #f="ngForm">
<label>Enter username:</label>
<input type="text" ngModel name="uname" placeholder="Userame"
class="form-control">
<label>Enter Password:</label>
<input type="password" name="upwd" placeholder="Password"
class="form-control">
<button type="submit" class = "btn btn-primary">Login</button>
</form>
</div>
#u=ngModel – is used to track validity, state and value.
State:
There are six types of states:
Touched – Default value is false
Untouched - Default value is True
Dirty - Default value is False. The value is changed when a value is
entered
Pristine - Default value is True.
<label>Touched: </label>{{u.touched}} <br>
<label>Untouched: </label>{{u.untouched}} <br>
<label>Dirty: </label>{{u.dirty}} <br>
<label>Pristine: </label>{{u.pristine}} <br>
Valid - Default value is False. True when the value is right
Invalid - Default value is False.
<input type="text" required ngModel name="uname"
#u="ngModel"placeholder="Userame" class="form-control">
<label>Valid </label>{{u.valid}} <br>
<label>Invalid: </label>{{u.invalid}} <br>
Checking for validity:
[class.v] = "u.valid"
Custom validation:
AbstractControl: AbstractControl is a class to read the value from input
element
ts file:
export function checkalphabet(txtval:AbstractControl)
{
var res = txtval.value
return res.startswith('A')?null: {msg:true }
}
HTML file:
address: new FormControl("",[checkalphabet])
Pipes/Filers:
Pipe takes the raw data as input and then transforms the raw data into the
desired format. Angular supports built-in and user defined types.
Types:
UpperCase
LowerCase
Slice
Number
Currency
Date
JSON
Percent
Async
Uppercase:
Transforms a string into uppercase
Ex:
<p>{{ ‘Carlos Menezes’ | uppercase}} </p>
Lowercase:
Transforms a string into uppercase
Ex:
<p>{{ ‘Carlos Menezes’ | lowercase}} </p>
Slice:
Alows us to display part of a list
slice:start[:end]
Ex:
<p>{{ ‘Carlos Menezes’ | slice: 0:5}} </p>
Number:
Allow us to format a number
number[:digitInfo]
<p>{{98745| number}}</p>
digit info:
<h2>{{5.678 | number:’1.2-3’}}</h2>
1 – min number of integer digit
2 – min number of decimal digit
3 - max number of decimal digits
<h2>{{5.678 | number:’3.4-5}}</h2>
005.6780
<h2>{{5.678 | number:’3.1-2}}</h2>
005.68
Percent:
Allow us to display a percentage
<p>{{0.5 | percent}} </p>
Date:
Allows us to format dates values into a string
<p>{{dateOfBirthday | date:’ddMMyyyy’}}</p>
<p>{{dateOfBirthday | date:’HHmmss’}}</p>
<p>{{dateOfBirthday | date:’longDate’}}</p> (and many more)
Ex:
{{‘1-1-2000 | date:longDate}}
1st January 2000
Currency:
Allows us to format an amount of money into currency
<p>{{51.5| currency:’EUR’}}</p>
EUR1.5
<p>{{51.5| currency:’USD’:true}}</p>
$51.5
<p>{{51.5| currency:’USD’:true:’.2’}}</p>
$51.50
Custom pipes:
Two types of pipes:
Pure pipes
Impure pipes
ng g pipe pipename
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'discount',
standalone: false
})
export class DiscountPipe implements PipeTransform {
transform(value: number, ...args: number[]): number {
return value - value *args[0]/100;
}
<div>{{i.price | discount:10 | currency:'INR'}}</div>
Routing:
<router-outlet></router-outlet>
Router-outlet acts as a placeholder for the navigation bar
error:string = ''
constructor(public r:Router){ //using the built-in class router --> to
navigate from one product to other
validate(frm:any){
if(frm.uname=="admin" && frm.upwd=="123"){
this.r.navigate(['products'])
}
else{
this.error = "Invalid username or password"
}
To guard a page
Create a guard file npx ng g guard filename
import { CanActivateFn } from '@angular/router';
export const securityGuard: CanActivateFn = (route, state) => {
return false;
};
app-routing.module:
{
path: 'buy',
component: BuyComponent,
canActivate: [securityGuard]
},
RXJS and HTTP Programming:
Fake server – JSON server
RXJS:
Reactive Extension for Javascript
RXJS is a library of angular for data handling
Observable:
It is like data streams(a continuous flow of data)
Observable is a class. It exposes the data to the user
Used to work with asynchronous (works independently) data (like data
coming from a server)
The data by the observable is available only when the user is
subscribed(requested) for it
Method returns Observable:
From – Emits data using array
Ex: const array$ = from([10,20,30]);
array$.subscribe(value => { //subscribing to the data
console.log(‘From array:’,value);
});
Interval – Emit numbers every few millisecond
const timer$ = interval(1000);
timer$.subscribe(val => {
console.log(‘Interval value:’,val);
FromEvent
Creating Observable
clickbutton(){
const button = document.getElementById('clickbtn')!;
const click$ = fromEvent(button,'click');
click$.subscribe(() => {
console.log('Button Clicked!');
});
}
<button (click) = "clickbutton()" id="clickbtn">Click</button>
Creating custom observable:
observabledemo(){
let ob = new Observable(obs =>{
obs.next('Hello');
obs.next('World');
obs.complete();
})
ob.subscribe({next: val => console.log(val),
complete:() => console.log('Done!')
});
}
<button (click) = " observabledemo()">Observable Click</button><br> <br>
emits data in asynchronousy
let ob = new Observable(sender) //emits a data
sender.next(“India”)
sender.next(“Canda”)
sender.next(“UAE”);
client:
sender.completed(“List is completed”);
ob.subscribe(result => { console.log(result) completed:com =>
console.log(com)
Create JSON database:
To work with real data
Step 1: Create a server “npm install -g json-server”
Step 2: Create data(in notepad)
Step 3: