Angular Notes
Angular Notes
Q) What is Data?
Data is collection of raw facts. Data may be text, audio, video, streaming data ,whenever we develop any
web application. Application is collection of files (code) Files namely: .html , .js , .css , .aspx , .php , .py ,
.jsp , etc…. we can develop web application by using Different Programming Languages, Technologies,
Frameworks, Database softwares, UI Technologies. After developing the application we have to deploy the
`application in webserver so that end user will access the application via Browser and internet .
Q) what is Web Browser?
Web Browser is a software which is used to access the files from webserver , Ex: - internet Explorer,
Mozilla Firefox, Google chrome
Q) what is web server?
Webserver is a software which provides services to different clients like Browsers, Mobiles etc...
Q) what web server consists of ?
Web application Ex:- IIS(internet information services),.net, Jboss, java,Apache, php, Django, java.
Web application: - The application that was deployed on webserver and can be accessible via Browser and
internet. Web applications are multi user applications
Web applications are of 2 Types:-
1. Static web application
2. Dynamic web application
Static web application: - The application whose output is common for all the users
Static web applications can be developed by using UI Technologies
Ex: - blogs, Movie review websites, w3schools
UI Technologies=HTML + JavaScript + CSS
HTML: - Display the content on Browser using (Headings, Paragraphs, Table, List, Link,
Frame, Form, etc,)
JavaScript :- is used to perform Operations on HTML Elements Validations, Logics
CSS--------> it is used to apply styles for HTML Elements Ex:- blogs,movie review websites ,w3schools
Dynamic web application:-The application whose output change based on user/ location/ time/ search
Dynamic web applications can be developed by using UI Technologies + Java/ .net/ Php / Python/ Angular.
Different Dynamic Web Applications:-
1. Ecommerce (amazon,flipkart,ebay)
2. Banking (icici,axis,citi)
3. insurance (health,vehicle,lic)
4. Socialnetworking(facebook,twitter,linkden)
5. Education (college,school,w3schools,jntu results,byjuice,examantaion,library )
6. Entertainment (Bookmyshow,amazon prime,netflix,hotstar)
7. services
public services: eseva, meseva, irctc, manabadi, incometax websites, apsrtc, tsrtc
private: redbus, abhibus, ola,swiggy
8. Healthcare
Web Application Architecture: whenever we develop dynamic web application we require Browser,
Webserver and Database server.
Technology Developed By
Javascript :- scripting Language Netscape
Jquery :- Javascript Library Microsoft
AnglarJS :- Javascript Framework Google
Typescript :- Programming Language Microsoft
Angular2,4,5,6,7,8,9 :-Typescript Framework Google
Prog Langs Technologies Frameworks Database s/ws
java servlets, JSP, JDBC Spring, ORM, Spring Boot, Rest Oracle, MySQL
C#.net ASP.net, ADo.net ASP.net MVC, WCF, WebAPI Sql Server
Entity Framework,
python -------------- Django, Flask Mongo dB
php Cakephp MYSQL
Web application Developers are classified into 2 Types:-
1. Full Stack Developer : - UI Technologies + Angular + Java/.net/Python/PHP+Database
2. Mean Stack Developer: - UI Technologies + Angular + nodejs + Expressjs + mongdb
After developing any webapplication we have to deploy the appn on webserver
so that enduser will access the application via Browser and internet
S/w companies
product s/w products service products
Microsoft typescript,win os,.net,sqlserver, Msoffice,Azure hotmail,skype,notepad.
Google angularjs, angular,andoid,gcp gmail,youtube, gpay,gdrive,gmaps
Facebook reactjs facebook,insta,whatsapp
amazon AWS amazon prime,amazon shoping cart
oracle java,oracle ----
some service based Companies: TCS,Wipro,Tech,accenture,csc,cognizent
S/w company-------->Develop applications---→Application is collection of programs.
Programming Languages :- C,C++,Java,C#.net,Typescript,python
Scripting Languages :- Javascript,Vbscript,python
Markup Languages :- HTML,HTML5
Library :- Jquery,ReactJS
Technologies :- ASP.net,ADO.net (.net), JSP,servelets,JDBC (java),PHP
Frameworks
Client Side Framework:-AngularJS, Angular2/4/5/6/7/8/9, Vuejs, Knockjs, backboneJS,ExpressJS, node.js
Server Side Frameworks:-spring,ASP.net,MVC,SpringBoot,Django,Flask,WCF,WEBAPI,.netcore,ASpCore
DataBase Softwares :- Sqlserver,Oracle,MySQL,Mongdb
Query Languages :- SQL,HQL,LINQ,PLSQL,TSQL
Design Patterns :-MVC,MVT,MVVM,Singleton,Factpory,DAO etc..
DataTransfer :- XML,JSON
Architecture :- 3Tier,NTier
Design Principles :- SOLID,ACID
CloudTechnologies :- AWS,Azure,salesForce
SDLC Lifecycles :- Waterfall,V-Model,Spiral,Rad,Azile model
Protocols :-Http,Https,TCP,FTP,SMTP
Design Patterns:- Design Pattern is a readymade solution for already existing problems
Framework:-Framework is a software that was developed by using a Design pattern and by using a Language.
These are of 2 types: MVT and MVC.
MVC(Design Pattern) MVT (component architecture)
C#.net java javascript python Typescript
ASP.net MVC Spring AngularJS Django Angular8
JRE=JVM+Library Classes and JDK=JRE+Development Tools
Development Tools are Editors which are used to develop appns
JVM:- Memory Management and execution of Java programs
.net Framework :- CLR+Base class Libraries
Development Tools:- Microsoft VisualStudio Editor
• TypeScript always highlights errors at compilation time during the time of development, whereas
JavaScript points out errors at the runtime.
• TypeScript runs on any browser or JavaScript engine.
Variables:
A variable is the storage location, which is used to store value/information to be referenced and used by
programs. It acts as a container for value in code and must be declared before the use. We can declare a
variable by using the var keyword in typescript. In TypeScript, the variable follows the same naming rule as
of JavaScript variable declaration. These rules are-
Variable is the name given for a particular memory location. The let keyword is similar to var keyword in
some respects, and const is an let which prevents re-assignment to a variable.
Q) What is the purpose of variable?
The purpose of variable is to store the value
Q) What is variable declaration?
Declaring the variable without assigning the value is called as variable declaration
var x:number;
Q) What is variable initialization?
Assigning the value to the variable at the time of declaring the variable is called as
variable initialization. ex: var x:number=10;
Q) What is variable Assignment?
Assigning the value to the variable after declaring the variable is called as
variable Assignment
var x:number;
x=10;
Variable Declaration
We can declare a variable in one of the four ways:
1. Declare type and value in a single statement
var [variablename: [datatype] = value;
2. Declare type without value. Then the variable will be set to undefined.
var [variablename] : [datatype];
3. Declare its value without datatype. Then the variable will be set to ‘any’ datatype.
var [variablename] = value;
4. Declare without value and type. Then the variable will be set to ‘any’ datatype and initialized with
‘undefined’ value. var [variablename];
In functional programming variables are divided into 2 Types
1. Global Variables
2. Local Variables
1.Global Variables:- The variables that are declared outside the function are called as Global Variables.
The scope of Global Variable is in multiple functions in functional programming we can declare variables
by using ‘var’ and ‘let’ keyword.
it is always recommended to declare Global variables with ‘var’’ keyword.
syntax:- var variablename:datatype=value;
Ex:- var x:number=10;
2. Local variable:- The variables that was declared inside the function are called as local variables. it is
always recommended to declare local variable with let keyword
if we declare variable with let keyword the scope is within the function
syntax:- let x:number=10;
Ex:-
var x:number=8; x,y are Global variables
var y:number=4;
function Add()
{
let sum:number=x+y; sum is localvariable
console.log(“sum is”+sum); scope is within the function
}
function Sub()
{
let diff:number=x-y; diff is local variable
console.log(“Diff is”+diff);
}
Output :
Sum is 12
Diff is 4
Let's understand all the three variable keywords one by one.
1.var keyword
Generally, var keyword is used to declare a variable in JavaScript. var x = 50;
We can also declare a variable inside the function:
function a() {
var msg = " Welcome to JavaTpoint !! ";
return msg;
}
a(); //function call
We can also access a variable of one function with the other function:
function a() {
var x = 50;
return function b() {
var y = x+5;
return y;
}
}
var c = a(); //55
b(); //returns '55'
Scoping rules
Variable with var keyword can be accessed through out the program because its recognised as global variable.
Example
function f()
{
var X = 5; //Available globally inside f()
if(true)
{
var Y = 10; //Available globally inside f()
console.log(X); //Output 5
console.log(Y); //Output 10
}
console.log(X); //Output 5
console.log(Y); //Output 10
}
f();
console.log(X); //Returns undefined because value cannot accesses from outside function
console.log(Y); //Returns undefined because value cannot accesses from outside function
let declarations
The let keyword is similar to the var keyword. The let keyword has some restriction in scoping in comparison
of the var keyword.
The let keyword can enhance our code readability and decreases the chance of programming error.
The let statement are written as same syntax as the var statement:
var declaration: var b = 50;
let declaration: let b = 50;
The key difference between var and let is not in the syntax, but it differs in the semantics (logic). The Variable
declared with the let keyword are scoped to the nearest enclosing block which can be smaller than a function
block.
Example
function f()
{
var X = 5; //Available globally inside f()
if(true)
{
let Y = 10; //Available locally inside if()
console.log(X); //Output 5
console.log(Y); //Output 10
}
console.log(X); //Output 5
console.log(Y); //error
}
f();
const declarations
The const declaration is used to declare permanent value, which cannot be changed later. It has a fixed value.
The const declaration follows the same scoping rules as let declaration, but we cannot re-assign any new value
to it.
Note: According to the naming standards, the const variable must be declared in capital letters. Naming
standards should be followed to maintain the code for the long run.
Example
function constTest(){
const VAR = 10;
console.log("Value is: " +VAR);
}
constTest();
Output:
Value is: 10
What will happen when we try to re-assign the const variable?
If we try to re-assign the existing const variable in a code, the code will throw an error. So, we cannot re-
assign any new value to an existing const variable.
Example
function constTest(){
const VAR = 10;
console.log("Output: " +VAR); // Output: 10
const VAR = 10;
console.log("Output: " +VAR); //Uncaught TypeError: Assignment to constant variable
}
constTest();
Output:
SyntaxError: Identifier 'VAR' has already been declared.
Var vs. Let Keyword
SNo Var Let
1. The var keyword was introduced with The let keyword was added in ES6 (ES 2015)
JavaScript. version of JavaScript.
3. It can be declared globally and can be It can be declared globally but cannot be accessed
accessed globally. globally.
4. Variable declared with var keyword can Variable declared with let keyword can be
be re-declared and updated in the same updated but not re-declared.
scope. Example:
Example:
function varGreeter(){
function Bhargav(){ let a = 10;
var a = 10; let a = 20; //SyntaxError:
var a = 20; //a is replaced //Identifier 'a' has already been declared
console.log(a); console.log(a);
} }
Bhargav(); varGreeter();
if-else statement:
The if statement only returns the result when the condition is true. But if we want to returns something when
the condition is false, then we need to use the if-else statement. The if-else statement tests the condition. If the
condition is true, it executes if block and if the condition is false, it executes the else block.
Syntax
if(condition) { // code to be executed }
else { // code to be executed }
Example
let n = 10
if (n > 0) { console.log("The input value is positive Number: " +n);
} else {
console.log("The input value is negative Number: " +n);
}
Output:
The input value is positive Number: 10
if-else-if ladder
Here a user can take decision among multiple options. It starts execution in a top-down approach. When the
condition gets true, it executes the associated statement, and the rest of the condition is bypassed. If it does
not find any condition true, it returns the final else statement.
Syntax
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
else{
//code to be executed if all the conditions are false
}
Example
let marks = 95;
if(marks<50){ console.log("fail"); }
else if(marks>=50 && marks<60){
console.log("D grade"); }
else if(marks>=60 && marks<70){
console.log("C grade"); }
else if(marks>=70 && marks<80){
console.log("B grade"); }
else if(marks>=80 && marks<90){
console.log("A grade"); }
else if(marks>=90 && marks<100){
console.log("A+ grade"); }
else{
console.log("Invalid!"); }
Output:
A+ grade
Nested if statement
Here, the if statement targets another if statement. The nested if statement means if statement inside the body
of another if or else statement.
Syntax
if(condition1) { //Nested if else inside the body of "if"
if(condition2) { //Code inside the body of nested "if" }
else { //Code inside the body of nested "else" }
}
else { //Code inside the body of "else." }
Example
let n1 = 10, n2 = 22, n3 = 25
if (n1 >= n2) {
if (n1 >= n3) { console.log("The largest number is: " +n1) }
else { console.log("The largest number is: " +n3) }
}
else {
if (n2 >= n3) { console.log("The largest number is: " +n2) }
else { console.log("The largest number is: " +n3) }
}
Output:
The largest number is: 25
TypeScript Switch Statement
The TypeScript switch statement executes one statement from multiple conditions. It evaluates an expression
based on its value that could be Boolean, number, byte, short, int, long, enum type, string, etc. A switch
statement has one block of code corresponding to each value. When the match is found, the corresponding
block will be executed. A switch statement works like the if-else-if ladder statement.
Syntax
1. switch(expression){
2. case expression1:
3. //code to be executed;
4. break; //optional
5. case expression2:
6. //code to be executed;
7. break; //optional
8. ........
9. default:
10. //when no case is matched, this block will be executed;
11. break; //optional
12. }
The switch statement contains the following things. There can be any number of cases inside a switch statement.
Case: The case should be followed by only one constant and then a semicolon. It cannot accept another variable or
expression.
Break: The break should be written at the end of the block to come out from the switch statement after executing
a case block. If we do not write break, the execution continues with the matching value to the subsequent case
block.
Default: The default block should be written at the end of the switch statement. It executes when there are no case
will be matched.
Example
1. let a = 3;
2. let b = 2;
3. switch (a+b){
4. case 1: { console.log("a+b is 1."); break; }
5. case 2: { console.log("a+b is 5."); break; }
6. case 3: { console.log("a+b is 6."); break; }
7. default: { console.log("a+b is 5."); break; }
8. }
Output:a+b is 5
In TypeScript, we can use the switch case with Enum in the following ways.
Example
1. enum Direction {
2. East,
3. West,
4. North,
5. South
6. };
7. var dir: DirectionDirection = Direction.North;
8. function getDirection() {
9. switch (dir) {
10. case Direction.North: console.log('You are in North Direction'); break;
11. case Direction.East: console.log('You are in East Direction'); break;
12. case Direction.South: console.log('You are in South Direction'); break;
13. case Direction.West: console.log('You are in West Direction'); break;
14. }
15. }
16. getDirection();
The TypeScript switch statement is fall-through. It means if a break statement is not present, then it executes
all statements after the first match case.
Example
1. let number = 20;
2. switch(number)
3. { //switch cases without break statements
4. case 10: console.log("10");
5. case 20: console.log("20");
6. case 30: console.log("30");
7. default: console.log("Not in 10, 20 or 30");
8. }
Output:20
30
Not in 10,20 or 30
TypeScript Indefinite Loops
In a programming language, loops are the sequence of instructions which continually repeated until a specific
condition is not found. It makes the code compact. We can mostly use it with the array. Below is the general
structure of the loop statement:
Indefinite Loop
In Indefinite loops, the number of iterations is not known before beginning the execution of the block of
statements. There are two indefinite loops:
1. while loop
2. do-while loop
TypeScript while loop
The TypeScript while loop iterates the elements for the infinite number of times. It executes the instruction
repeatedly until the specified condition evaluates to true. We can use it when the number of iteration is not
known. The while loop syntax is given below.
Syntax
While loop starts the execution with checking the condition. If the condition evaluates to true, the loop body
statement gets executed. Otherwise, the first statement following the loop gets executed. If the condition
becomes false, the loops get terminated, which ends the life-cycle of the loops.
Example
1. let num = 4;
2. let factorial = 1;
3. while(num >=1) {
4. factorialfactorial = factorial * num;
5. num--;
6. }
7. console.log("The factorial of the given number is: "+factorial);
The TypeScript do-while loop iterates the elements for the infinite number of times similar to the while loop.
But there is one difference from while loop, i.e., it gets executed at least once whether the condition is true or
false. It is recommended to use do-while when the number of iteration is not fixed, and you have to execute
the loop at least once. The do-while loop syntax is given below.
Syntax
The do-while loop starts executing the statement without checking any condition for the first time. After the
execution of the statement and update of the variable value, it starts evaluating the condition. If the condition
is true, the next iteration of the loop starts execution. If the condition becomes false, the loops get terminated,
which ends the life-cycle of the loops.
Example
1. let n = 10;
2. do { console.log(n);
3. n++;
4. } while(n<=15);
Output: 10
11
12
13
14
15
TypeScript Definite Loop
In this loop, we know about the number of iterations before the execution of the block of statements. A "for
loop" is the best example of this loop. Here, we are going to discuss three types of the loop:
1. for loop
2. for..of loop
3. for..in loop
Example
The for..of loop is used to iterate and access the elements of an array, string, set, map, list, or tuple collection.
The syntax of the for..of loop is given below.
Syntax
Example
The for..in loop is used with an array, list, or tuple. This loop iterates through a list or collection and returns
an index on each iteration. In this, the data type of "val" should be a string or any. The syntax of the for..in
loop is given below.
Syntax
Example
Both the loops iterate over the lists, but their kind of iteration is different. The for..in loop returns a list of
indexes on the object being iterated, whereas the for..of loop returns a list of values of the object being
iterated.Below example demonstrates these differences:
Output:
TypeScript Operators
An Operator is a symbol which operates on a value or data. It represents a specific action on working with data. The
data on which operators operates is called operand. It can be used with one or more than one values to produce a
single value. All of the standard JavaScript operators are available with the TypeScript program.
Example
a=10;
b=10;
a + b = 20;
In the above example, the values '10' and '20' are known as an operand, whereas '+' and '=' are known as operators.
Operators in Typescript
In TypeScript, an operator can be classified into the following ways.
Arithmetic operators, Comparison (Relational) operators, Logical operators, Bitwise operators, Assignment
operators, Ternary/conditional operator, Concatenation operator, Type Operator.
Arithmetic Operators
Arithmetic operators take numeric values as their operands, performs an action, and then returns a single numeric
value. The most common arithmetic operators are addition(+), subtraction(-), multiplication(*), and division(/).
The comparison operators are used to compares the two operands. These operators return a Boolean value true
or false. The important comparison operators are given below.
=== Identical(equal It checks whether the type and values let a = 10;
and of the same of the two operands are equal or not. let b = 20;
type) console.log(a===b); //false
console.log(a===10); //true
console.log(10==='10'); //false
!= Not equal to It checks whether the values of the two let a = 10;
operands are equal or not. let b = 20;
console.log(a!=b); //true
console.log(a!=10); //false
console.log(10!='10'); //false
!== Not identical It checks whether the type and values let a = 10;
of the two operands are equal or not. let b = 20;
console.log(a!==b); //true
console.log(a!==10); /false
console.log(10!=='10'); //true
> Greater than It checks whether the value of the left let a = 30;
operands is greater than the value of let b = 20;
the right operand or not. console.log(a>b); //true
console.log(a>30); //false
console.log(20> 20'); //false
>= Greater than or It checks whether the value of the left let a = 20;
equal to operands is greater than or equal to the let b = 20;
value of the right operand or not. console.log(a>=b); //true
console.log(a>=30); //false
console.log(20>='20'); //true
< Less than It checks whether the value of the left let a = 10;
operands is less than the value of the let b = 20;
right operand or not. console.log(a<b); //true
console.log(a<10); //false
console.log(10<'10'); //false
<= Less than or It checks whether the value of the left let a = 10;
equal to operands is less than or equal to the let b = 20;
value of the right operand or not. console.log(a<=b); //true
console.log(a<=10); //true
console.log(10<='10'); //true
Logical Operators
Logical operators are used for combining two or more condition into a single expression and return the
Boolean result true or false. The Logical operators are given below.
Operator Operator_Na Description Example
me
Bitwise Operators
The bitwise operators perform the bitwise operations on operands. The bitwise operators are as follows.
>> Bitwise Right Shift The left operand's value is moved to the let a = 2;
right by the number of bits specified in let b = 3;
the right operand. let c = a >> b;
console.log(c); //Output 0
<< Bitwise Left Shift The left operand's value is moved to the let a = 2;
left by the number of bits specified in the let b = 3;
right operand. New bits are filled with let c = a << b;
zeroes on the right side. console.log(c); //Output 16
>>> Bitwise Right Shift The left operand's value is moved to the let a = 3;
with Zero right by the number of bits specified in let b = 4;
the right operand and zeroes are added let c = a >>> b;
on the left side. console.log(c); //Output 0
Assignment Operators
Assignment operators are used to assign a value to the variable. The left side of the assignment operator is
called a variable, and the right side of the assignment operator is called a value. The data-type of the variable
and value must be the same otherwise the compiler will throw an error. The assignment operators are as
follows.
Ternary/Conditional Operator
The conditional operator takes three operands and returns a Boolean value based on the condition, whether it
is true or false. Its working is similar to an if-else statement. The conditional operator has right-to-left
associativity. The syntax of a conditional operator is given below.
Example
1. let num = 16;
2. let result = (num > 0) ? "True":"False"
3. console.log(result);
Output: True
Concatenation Operator
The concatenation (+) operator is an operator which is used to append the two string. In concatenation
operation, we cannot add a space between the strings. We can concatenate multiple strings in a single
statement. The following example helps us to understand the concatenation operator in TypeScript.
Example
1. let message = "Welcome to " + "JavaTpoint";
2. console.log("Result of String Operator: " +message); Output:Result of String Operator: Welcome to
JavaTpoint
Type Operators
There are a collection of operators available which can assist you when working with objects in TypeScript.
Operators such as typeof, instanceof, in, and delete are the examples of Type operator. The detail explanation
of these operators is given below.
In It is used to check for the let Bike = {make: 'Honda', model: 'CLIQ',
existence of a property on an year: 2018};
object. console.log('make' in Bike); //
Output:true
typeof It returns the data type of the let message = "Welcome to " + "JavaTpoint";
operand. console.log(typeof message); //
Output:String
TypeScript DataTypes
The TypeScript language supports different types of values. It provides data types for the JavaScript to
transform it into a strongly typed programing language. JavaScript doesn't support data types, but with the
help of TypeScript, we can use the data types feature in JavaScript. TypeScript plays an important role when
the object-oriented programmer wants to use the type feature in any scripting language or object-oriented
programming language. TypeScript provides data types as an optional Type System. We can classify the
TypeScript data type as following.
1. Static Types
In the context of type systems, static types mean "at compile time" or "without running a program." In a
statically typed language, variables, parameters, and objects have types that the compiler knows at compile
time. The compiler used this information to perform the type checking. Static types can be further divided into
two sub-categories:
The TypeScript has five built-in data types, which are given below.
Number
Like JavaScript, all the numbers in TypeScript are stored as floating-point values. These numeric values are
treated like a number data type. The numeric data type can be used to represents both integers and fractions.
TypeScript also supports Binary(Base 2), Octal(Base 8), Decimal(Base 10), and Hexadecimal(Base 16)
literals.
1. MAX_VALUE It returns the largest possible value of a number in JavaScript and can
have 1.7976931348623157E+308.
2. MIN_VALUE It returns the smallest possible value of a number in JavaScript and can
have 5E-324.
Example
1. console.log("Number Properties: ");
2. console.log("A number variable can hold maximum value: " + Number.MAX_VALUE);
3. console.log("A number variable can hold minimum value: " + Number.MIN_VALUE);
4. console.log("Value of Negative Infinity: " + Number.NEGATIVE_INFINITY);
5. console.log("Value of Positive Infinity:" + Number.POSITIVE_INFINITY);
6. console.log("Example of NaN: " +Math.sqrt(-5)); // NaN
Output:Number Properties:
SN Method_Name Description
5. toString() It is used to return the string representation of the number in the specified base.
Example
1. let myNumber: number = 12345;
2. let myNumber_1: number = 12.8789;
3. let myNumber_2: number = 12667.976;
4. let myNumber_3: number = 12.5779;
5. let myNumber_4: number = 1234;
6. let myNumber_5 = new Number(123);
7. console.log("Number Method: toExponential()");
8. console.log(myNumber.toExponential());
9. console.log(myNumber.toExponential(2));
10. console.log("Number Method: toString()");
11. console.log(myNumber.toString());
12. console.log(myNumber.toString(4));
13. console.log("Number Method: toFixed()");
14. console.log(myNumber_1.toFixed());
15. console.log(myNumber_1.toFixed(3));
16. console.log("Number Method: toLocaleString()");
17. console.log(myNumber_2.toLocaleString()); // returns in US English
18. console.log("Number Method: toPrecision()");
19. console.log(myNumber_3.toPrecision(1));
20. console.log(myNumber_3.toPrecision(3));
21. console.log("Number Method: tovalueOf()");
22. console.log(myNumber_5)
23. console.log(myNumber_5.valueOf())
24. console.log(typeof myNumber)
Output:
We will use the string data type to represents the text in TypeScript. String type work with textual data. We
include string literals in our scripts by enclosing them in single or double quotation marks. It also represents
a sequence of Unicode characters. It embedded the expressions in the form of $ {expr/variablename}.
Syntax let identifier: string = " "; Or let identifier: string = ' ';
Examples
In TypeScript, the string is an object which represents the sequence of character values. It is a primitive data
type which is used to store text data. The string values are surrounded by single quotation mark or double
quotation mark. An array of characters works the same as a string.
Output:
3. Back-ticks strings
It is used to write an expression. We can use it to embed the expressions inside the string. It is also known as
Template string. TypeScript supports Template string from ES6 version.
Example
Output:
ES6 provides us to write the multi-line string. We can understand it from the below example.
Example
1. let multi = 'hello ' +
2. 'world ' +
3. 'my ' +
4. 'name ' +
5. 'is ' +
6. 'Rohit';
If we want that each line in the string contains "new line" characters, then we have to add "\n" at the end of
each string.
Example
1. let multi = ' hello\n ' +
2. 'JavaTpoint\n ' +
3. 'my\n ' +
4. 'name\n ' +
5. 'is\n ' +
6. 'Rohit Sharma';
7. console.log(multi);
Output:
hello
JavaTpoint
my
name
is
Rohit Sharma
String Literal Type
A string literal is a sequence of characters enclosed in double quotation marks (" "). It is used to represent a
sequence of character which forms a null-terminated string. It allows us to specify the exact string value
specified in the "string literal type." It uses "pipe" or " | " symbol between different string value.
1. Variable Assignment We can assign only allowed values to a literal type variable. Otherwise, it will give
the compile-time error.
Example
Output:
Correct
compilation error
2. Function Parameter We can pass only defined values to literal type argument. Otherwise, it will give the
compile-time error.
Example
Output:
Mango
Banana
String Methods
SN Method Description
5. indexOf() It returns the index of the first occurrence of the specified substring from a
string, otherwise returns -1.
6. lastIndexOf() It returns the index of the last occurrence of a value in the string.
11. split() It splits the string into substrings and returns an array.
13. toLowerCase() It converts the all characters of a string into lower case.
14. toUpperCase() It converts the all characters of a string into upper case.
15. trim() It is used to trims the white space from the beginning and end of the string.
16. trimLeft() It is used to trims the white space from the left side of the string.
17. trimRight() It is used to trims the white space from the right side of the string.
18. valueOf() It returns a primitive value of the specified object.
Example
1. //String Initialization
2. let str1: string = 'Hello';
3. let str2: string = 'JavaTpoint';
4. //String Concatenation
5. console.log("Combined Result: " +str1.concat(str2));
6. //String charAt
7. console.log("Character At 4: " +str2.charAt(4));
8. //String indexOf
9. console.log("Index of T: " +str2.indexOf('T'));
10. //String replace
11. console.log("After Replacement: " +str1.replace('Hello', 'Welcome to'));
12. //String uppercase
13. console.log("UpperCase: " +str2.toUpperCase());
Output:
Boolean
The string and numeric data types can have an unlimited number of different values, whereas the Boolean
data type can have only two values. They are "true" and "false." A Boolean value is a truth value which
specifies whether the condition is true or not.
Syntax let variablename: boolean = Booleanvalue;
Examples: let isDone: boolean = false;
Void
A void is a return type of the functions which do not return any type of value. It is used where no data type
is available. A variable of type void is not useful because we can only assign undefined or null to them. An
undefined data type denotes uninitialized variable, whereas null represents a variable whose value is
undefined.
Syntax let unusable: void = undefined;
Examples
1. function helloUser(): void {
alert("This is a welcome message");
}
2. let tempNum: void = undefined;
tempNum = null;
tempNum = 123; //Error
Null
Null represents a variable whose value is undefined. Much like the void, it is not extremely useful on its
own. The Null accepts the only one value, which is null. The Null keyword is used to define the Null type in
TypeScript, but it is not useful because we can only assign a null value to it.
Examples
1. let num: number = null;
2. let bool: boolean = null;
3. let str: string = null;
Undefined
The Undefined primitive type denotes all uninitialized variables in TypeScript and JavaScript. It has only
one value, which is undefined. The undefined keyword defines the undefined type in TypeScript, but it is not
useful because we can only assign an undefined value to it.
Example
1. let num: number = undefined;
2. let bool: boolean = undefined;
3. let str: string = undefined;
Any Type
It is the "super type" of all data type in TypeScript. It is used to represents any JavaScript value. It allows us
to opt-in and opt-out of type-checking during compilation. If a variable cannot be represented in any of the
basic data types, then it can be declared using "Any" data type. Any type is useful when we do not know
about the type of value (which might come from an API or 3rd party library), and we want to skip the type-
checking on compile time.
Syntax let identifier: any = value;
Examples
1. 1. let val: any = 'Hi';
2. val = 555; // OK
3. val = true; // OK
1. 2. function ProcessData(x: any, y: any) {
2. return x + y;
3. }
4. let result: any;
5. result = ProcessData("Hello ", "Any!"); //Hello Any!
6. result = ProcessData(2, 3); //5
User-Defined DataType
Array
An array is a collection of elements of the same data type. Like JavaScript, TypeScript also allows us to
work with arrays of values. An array can be written in two ways:
1. Use the type of the elements followed by [] to denote an array of that element type:
var list : number[] = [1, 3, 5];
2. The second way uses a generic array type:
var list : Array<number> = [1, 3, 5];
An array is a homogenous collection of similar type of elements which have a contiguous memory location.
An array is a user-defined data type.
An array is a type of data structure where we store the elements of a similar data type. In an array, we can store only
a fixed set of elements. We can also use it as an object.
The array is index-based storage, where the first element stored at index 0. The below structure helps to understand
the structure of an array.
Characteristics of an Array
1. An array stores elements which have the same data type.
2. Array elements stored in contiguous memory locations.
3. The storage of 2-D array elements is rowed by row in a contiguous memory location.
4. Array name represents the address of the starting element.
5. The size of an array should be initialized at the declaration time.
6. Array size should be a constant expression and not a variable.
7. We can retrieve array elements by specifying the element's corresponding index value.
Advantage
Code Optimization: An array helps to make the code optimized, which increases the speed and performance
of the program. It allows us to retrieve or sort the array data more efficiently.
Random access: It provides the ability to access any data of an array in constant time (independent of its
position and size). Thus, we can get any data of an array located at any index position directly.
Disadvantage
Size Limit: An array allows us to store only the fixed number of elements. Once the array is declared, we
cannot alter its size. Hence, if we want to insert more element than declared, it is not possible.
Array declaration
Just like JavaScript, TypeScript also supports arrays. There are two ways to declare an array:
1. Single-Dimensional Array
2. Multi-Dimensional Array
Single-Dimensional Array
A single-dimensional array is a type of linear array, which contains only one row for storing data. It has a
single set of the square bracket ("[]"). We can access its elements either using row or column index.
Example
1. let arr:number[];
2. arr = [1, 2, 3, 4]
3. console.log("Array[0]: " +arr[0]);
4. console.log("Array[1]: " +arr[1]);
Output:
Array[0]: 1
Array[1]: 2
Multi-Dimensional Array
A multi-dimensional array is an array which contains one or more arrays. In the multi-dimensional array, data
is stored in a row and column-based index (also known as matrix form). A two-dimensional array (2-D array)
is the simplest form of a multi-dimensional array.
Initialization
let arr_name:datatype[initial_array_index][referenced_array_index] = [ [val1,val2,val 3], [v1,v2,v3]];
Example
Output:
1
2
3
5
6
7
Array Object
Array objects allow us to store multiple values in a single variable. We can create an array by using the Array
object. The Array constructor is used to pass the following arguments for array creation.
Example
Output:
JavaTpoint
2200
Java
Abhishek
Array Traversal by using a for...in loop
Example
1. let i:any;
2. let arr:string[] = ["JavaTpoint", "2300", "Java", "Abhishek"];
3. for(i in arr) {
4. console.log(arr[i])
5. }
Output:
JavaTpoint
2300
Java
Abhishek
Passing Arrays to Functions
We can pass arrays to functions by specifying the array name without an index.
Example
Output:
JavaTpoint
2300
Java
Abhishek
TypeScript Spread operator
The spread operator is used to initialize arrays and objects from another array or object. We can also use it for
object de-structuring. It is a part of the ES 6 version.
Example
Output:
CopiedArray: 1,2,3
NewArray: 1,2,3,7,8
MergedArray: 1,2,3,4,5,6
Array Methods
1. concat() It is used to joins two arrays and returns the combined result.
3. every() It returns true if every element in the array satisfies the provided testing
function.
4. fill() It fills an array with a static value from the specified start to end index.
5. indexOf() It returns the index of the matching element in the array, otherwise -1.
6. includes() It is used to check whether the array contains a certain element or not.
12. Shift() It is used to removes and returns the first element of an array.
17. unshift() It is used to add one or more elements to the beginning of an array.
Tuple
The Tuple is a data type which includes two sets of values of different data types. It allows us to express an
array where the type of a fixed number of elements is known, but they are not the same. For example, if we
want to represent a value as a pair of a number and a string, then it can be written as:
1. // Declare a tuple
2. let a: [string, number];
3. // Initialize it
4. a = ["hi", 8, "how", 5]; // OK
TypeScript Tuples
We know that an array holds multiple values of the same data type. But sometimes, we may need to store a
collection of values of different data types in a single variable. Arrays will not provide this feature, but
TypeScript has a data type called Tuple to achieve this purpose. A Tuple is an array which store multiple fields
belong to different data types. It is similar to the structures in the C programming language.
A tuple is a data type which can be used like any other variables. It represents the heterogeneous collection of
values and can also be passed as parameters in a function call.
In abstract mathematics, the term tuple is used to denote a multi-dimensional coordinate system. JavaScript
does not have tuple as data type, but tuples are available in TypeScript. The order of elements in a tuple is
important.
Syntax
1. let tuple_name = [val1,val2,val3, ...val n];
Example
1. let arrTuple = [101, "JavaTpoint", 105, "Abhishek"];
2. console.log(arrTuple);
Output:
We can also declare and initialize a tuple separately by initially declaring the tuple as an empty tuple in
Typescript.
Example
1. let arrTuple = [];
2. arrTuple[0] = 101
3. arrTuple[1] = 105
Accessing tuple Elements
We can read or access the fields of a tuple by using the index, which is the same as an array. In Tuple, the
index starts from zero.
Example
1. let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
2. console.log("Name of the Employee is : "+empTuple [0]);
3. console.log("Age of the Employee is : "+empTuple [1]);
4. console.log(empTuple [0]+" is working in "+empTuple [2]);
Output:
Example
Output:
Output:
Tuples are mutable, which means we can update or change the values of tuple elements. To modify the fields
of a Tuple, we need to use the index of the fields and assignment operator. We can understand it with the
following example.
Example
1. let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
2. empTuple[1] = 30;
3. console.log("Name of the Employee is: "+empTuple [0]);
4. console.log("Age of the Employee is: "+empTuple [1]);
5. console.log(empTuple [0]+" is working in "+empTuple [2]);
Output:
We cannot delete the tuple variable, but its fields could be cleared. To clear the fields of a tuple, assign it with
an empty set of tuple field, which is shown in the following example.
Example
1. let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
2. empTuple = [];
3. console.log(empTuple);
Output:[]
Destructuring allows us to break up the structure of an entity. TypeScript used destructuring in the context of
a tuple.
Example
1. let empTuple = ["Rohit Sharma", 25, "JavaTpoint"];
2. let [emp, student] = empTuple;
3. console.log(emp);
4. console.log(student);
Output:
Rohit Sharma
25
Passing Tuple to Functions
We can pass a tuple to functions, which can be shown in the below example.
Example
1. //Tuple Declaration
2. let empTuple = ["JavaTpoint", 101, "Abhishek"];
3. //Passing tuples in function
4. function display(tuple_values:any[]) {
5. for(let i = 0;i<empTuple.length;i++) { console.log(empTuple[i]); }}
6. //Calling tuple in function
7. display(empTuple);
Output:
JavaTpoint
101
Abhishek
Interface
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow,
means a class which implements an interface is bound to implement all its members. It cannot be instantiated
but can be referenced by the class which implements it. The TypeScript compiler uses interface for type-
checking that is also known as "duck typing" or "structural subtyping."
Example
Enums define a set of named constant. TypeScript provides both string-based and numeric-based enums. By
default, enums begin numbering their elements starting from 0, but we can also change this by manually
setting the value to one of its elements. TypeScript gets support for enums from ES6.
Example
Enums stands for Enumerations. Enums are a new data type supported in TypeScript. It is used to define the
set of named constants, i.e., a collection of related values. TypeScript supports both numeric and string-
based enums. We can define the enums by using the enum keyword.
Numeric Enums
Numeric enums are number-based enums, which store values as numbers. It means we can assign the number
to an instance of the enum.
Example
1. enum Direction {
2. Up = 1,
3. Down,
4. Left,
5. Right, }
6. console.log(Direction);
In the above example, we have a numeric enum named Direction. Here, we initialize Up with 1, and all of
the following members are auto-incremented from that point. It means Direction.Up has the value
1, Down has 2, Left has 3, and Right has 4.
Output:
According to our need, it also allows us to leave off the initialization of enumeration. We can declare the enum
without initialization as below.
1. enum Direction {
2. Up,
3. Down,
4. Left,
5. Right,}
6. console.log(Direction);
Here, Up have the value 0, and all of the following members are auto-incremented from that point. It means
Direction.Up has the value 0, Down has 1, Left has 2, and Right has 3. The auto-incrementing behavior is
useful when there is no need to care about the member values themselves. But each value must
be distinct from other values in the same enum.
Output:
In TypeScript enums, it is not necessary to assign sequential values to enum members always. We can provide
any values to the enum members, which looks like the below example.
Example
1. enum Direction {
2. Up=1,
3. Down=3,
4. Left=6,
5. Right=10,
6. }
7. console.log(Direction);
Output:
We can also use an enum as a function type or return type, which we can see in the below example.
1. enum AppStatus {
2. ACTIVE,
3. INACTIVE,
4. ONHOLD
5. }
6. function checkStatus(status: AppStatus): void {
7. console.log(status);
8. }
9. checkStatus(AppStatus.ONHOLD);
In the above example, we have declared an enum AppStatus. Next, we create a function checkStatus() that
takes an input parameter status which returns an enum AppStatus. In the function, we check for the type of
status. If status name matches, we get the matched enum member.
Output: 2
Here, we can see that the value printed '2' in the last statement is not much useful in most of the scenarios.
That's why it is preferred and recommended to use string-based enums.
String Enums
String enums are a similar concept to numeric enums, except that the enum has some subtle runtime
differences. In a string enum, each enum values are constant-initialized with a string literal, or with another
string enum member rather than numeric values. String enums do not have auto-incrementing behavior. The
benefits of using this enum is that string enums provides better readability. If we were debugging a program,
string enums allow us to give a meaningful and readable value when our code runs, independent of the name
of the enum member itself. Consider the following example of a numeric enum, but it is represented as a string
enum:
Example
1. enum AppStatus {
2. ACTIVE = 'ACT',
3. INACTIVE = 'INACT',
4. ONHOLD = 'HLD',
5. ONSTOP = 'STOP' }
6. function checkStatus(status: AppStatus): void {
7. console.log(status); }
8. checkStatus(AppStatus.ONSTOP);
Output: STOP
In the above example, we have declared a string enum AppStatus with the same values as the numeric enum
above. But string enum is different from numeric enum where string enum values are initialized with string
literals. The difference between these enums is that the numeric enum values are auto-incremented, whereas
string enum values need to be initialized individually.
Heterogeneous Enums
The heterogeneous enums are enums, which contains both string and numeric values. But it is advised that
you don't do this unless there is a need to take advantage of JavaScript runtime behavior.
Example
1. enum AppStatus {
2. ACTIVE = 'Yes',
3. INACTIVE = 1,
4. ONHOLD = 2,
5. ONSTOP = 'STOP'
6. }
7. console.log(AppStatus.ACTIVE);
8. console.log(AppStatus.ONHOLD);
Output:
Computed and constant members
We know that each enum members has a value associated with it. These values can be either constant or
computed. We can consider enum member as constant if:
1. It is the first member of the enum and has no initializer value. In this case, it is assigned the value 0.
Example
1. // Name.Abhishek is constant:
2. enum Name {
3. Abhishek }
4. console.log(Name);
2. It has no initializer value, and the preceding enum member is a numeric constant. In this case, the value of
the current enum member will be the value of the preceding enum member plus one.
In all other cases, the enum member is considered computed. The following enum example includes enum
members with computed values.
1. enum Weekend {
2. Friday = 1,
3. Saturday = getDate('Dominoz'),
4. Sunday = Saturday * 40 }
5.
6. function getDate(day : string): number {
7. if (day === 'Dominoz') {
8. return 3; }
9. }
10. console.log(Weekend.Saturday);
11. console.log(Weekend.Sunday);
Output:3
120
Reverse mapping: TypeScript enums also support reverse mapping. It means we can access the value of an enum
member, and also can access a member name from its value. We can understand the reverse mapping from the
below example.
Example
1. enum Weekend {
2. Friday = 1,
3. Saturday,
4. Sunday }
5. console.log(Weekend.Saturday);
6. console.log(Weekend["Saturday"]);
7. console.log(Weekend[3]);
Output:2
2
Sunday
Enums at runtime
Enums are the real objects which exist at runtime. We can understand it from the below example.
1. enum E {
2. A, B, C}
It can actually be passed around to functions, which we can see in the below example.
We can use ambient enums for describing the shape of already existing enum types.
TypeScript Union
In TypeScript, we can define a variable which can have multiple types of values. In other words, TypeScript
can combine one or two different types of data (i.e., number, string, etc.) in a single type, which is called a
union type. Union types are a powerful way to express a variable with multiple types. Two or more data types
can be combined by using the pipe ('|') symbol between the types.
Syntax
1. (type1 | type2 | type3 | ........ | type-n)
Example
1. let value: number|string;
2. value = 120;
3. console.log("The Numeric value of a value is: "+value);
4. value = "Welcome to JavaTpoint";
5. console.log("The String value of a value is: "+value);
Output:
Output:
TypeScript allows passing a union type to an array. We can understand it from the below example.
Example
1. let arrType:number[]|string[];
2. let i:number;
3. arrType = [1,2,3,4];
4. console.log("Numeric type array:")
5. for(i = 0;i<arrType.length;i++){
6. console.log(arrType[i]); }
7. arrType = ["India","America","England"];
8. console.log("String type array:")
9. for(i = 0;i<arrType.length;i++){
10. console.log(arrType[i]); }
Output:
TypeScript map is a new data structure added in ES6 version of JavaScript. It allows us to store data in a key-value
pair and remembers the original insertion order of the keys similar to other programming languages. In
TypeScript map, we can use any value either as a key or as a value.
Create Map
We can create a map as below.
1. var map = new Map();
Map methods
SN Methods Descriptions
2. map.get(key) It is used to retrieve entries from the map. It returns undefined if the key
does not exist in the map.
3. map.has(key) It returns true if the key is present in the map. Otherwise, it returns false.
Example
Output:
When we execute the above code snippet, it returns the following output.
We can iterate over map keys or values or entries by using 'for...of' loop. The following example helps to
understand it more clearly.
Example
Output:
TypeScript Set
TypeScript set is a new data structure added in ES6 version of JavaScript. It allows us to store distinct
data (each value occur only once) into the List similar to other programming languages. Sets are a bit similar
to maps, but it stores only keys, not the key-value pairs.
SN Methods Descriptions
2. set.has(value) It returns true if the value is present in the set. Otherwise, it returns false.
Example: We can understand the set methods from the following example.
Output: When we execute the above code snippet, it returns the following output.
TypeScript set method also allows the chaining of add() method. We can understand it from the below
example.
Example
We can iterate over set values or entries by using 'for...of' loop. The following example helps to understand it
more clearly.
Example
Output:
TypeScript Functions:
Typescript is used to develop functional programming and object oriented programming.
Q)what is a function?
function is a subprogram which is used to perform a specific operation. Function will gets executed when
we call it single function is used to perform single operation .Functions ensure that our program is readable,
maintainable, and reusable. A function declaration has a function's name, return type, and parameters.
Advantage of function: These are the main advantages of functions.
o Code reusability: We can call a function several times without writing the same block of code again.
The code reusability saves time and reduces the program size.
o Less coding: Functions makes our program compact. So, we don't need to write many lines of code
each time to perform a common task.
o Easy to debug: It makes the programmer easy to locate and isolate faulty information.
Function Aspects
There are three aspects of a function.
Function declaration: A function declaration tells the compiler about the function name, function parameters,
and return type. The syntax of the function declaration is:
function functionName( [arg1, arg2, ...argN] );
Function definition: It contains the actual statements which are going to executes. It specifies what and how a
specific task would be done. The syntax of the function definition is:
function functionName( [arg1, arg2, ...argN] ){ //code to be executed }
Function call: We can call a function from anywhere in the program. The parameter/argument cannot differ in
function calling and a function declaration. We must pass the same number of functions as it is declared in the
function declaration. The syntax of the function call is:
FunctionName();
Different Types of functions:-
1. Named functions
2. Anonymous functions
3. Arrow Functions
named functions:- declaring the function with some name
syntax:-
function functionname([arguments]) { logic }
syntax to call the function:- functionname();
function will take i/p from use and return some value .At the time of declaring the function we have to
declare parameters and at the time of calling the function we have to pass values.The no of values,order of
values ,type of values that we pass must match with no of parameters,order of parameters,type of parameters.
Example//Function Definition
Rest Parameter:-It is used to pass zero or more values to a function. We can declare it by prefixing the three
"dot" characters ('...') before the parameter. It allows the functions to have a different number of arguments
without using the arguments object. The TypeScript compiler will create an array of arguments with the rest
parameter so that all array methods can work with the rest parameter. The rest parameter is useful, where we
have an undetermined number of parameters.
Rules to follow in rest parameter:
We can use only one rest parameter in a function.
It must be an array type.
It must be the last parameter in a parameter list.
function sum(a: number,...b: number[]): number {
let result = a;
for (var i = 0; i < b.length; i++) { result =result+ b[i]; }
return result;
}
let result1 = sum(3, 5);
let result2 = sum(3, 5, 7, 9);
console.log(result1 +"\n" + result2);
Output: 8
24
2. Anonymous functions:-Declaring the function without any name is called as Anonymous function
Anonymous function is also called as nameless function
we will assign function to variable
named function:- Anonymous function:-
function f1() var x=function()
{ {
console.log("hi hru"); console.log("hi hru");
} }
f1(); x();
Parameterized Anonymous function:
we need to assign Anonymous Function to variable
var sum:number=function(x:number,y:number)
{
let sum:number=x+y;
console.log(x+y); } sum(6,3);
3. Arrow functions or Lambda Expression :-
Arrow function:-Arrow function is the shorthand syntax of Anonymous function
syntax:-
()=>logic;
lambda operator (or) goes to
i/p=> logic
Left hand side we have to declare parameters
Right hand side we have to write Logic
var x=()=>console.log("i am without parameter");
x();
====================
var sum=(x,y)=>console.log(x+y);
sum(6,3); //9
====================
var sum=(x,y)=> x+y; //indicates returning value
var s=sum(6,3);
console.log(s); //9
======================
2. Generic
Generic is used to create a component which can work with a variety of data type rather than a single one. It
allows a way to create reusable components. It ensures that the program is flexible as well as scalable in the
long term. TypeScript uses generics with the type variable <T> that denotes types. The type of generic
functions is just like non-generic functions, with the type parameters listed first, similarly to function
declarations.
Example
A decorator is a special of data type which can be attached to a class declaration, method, property, accessor,
and parameter. It provides a way to add both annotations and a meta-programing syntax for classes and
functions. It is used with "@" symbol.
A decorator is an experimental feature which may change in future releases. To enable support for the
decorator, we must enable the experimentalDecorators compiler option either on the command line or in
our tsconfig.json.
Example
1. function f() {
2. console.log("f(): evaluated");
3. return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
4. console.log("f(): called");
5. } }
6. class C { @f() method() {} }
TypeScript forEach
The forEach() method is an array method which is used to execute a function on each item in an array. We can use
it with the JavaScript data types like Arrays, Maps, Sets, etc. It is a useful method for displaying elements in an array.
Syntax
We can declare the forEach() method as below.
array.forEach(callback[, thisObject]);
The forEach() method executes the provided callback once for each element present in the array in ascending
order.
Parameter Details
1. callback: It is a function used to test for each element. The callback function accepts three arguments, which
are given below.
Element value: It is the current value of the item.
Element index: It is the index of the current element processed in the array.
Array: It is an array which is being iterated in the forEach() method.
object:-object is an instance of class. instance means allocating memory for instance variables
i.e whenever we create object for a class then memory will allocate for instance variables
syntax to create object:-
var objectname:classname=new classname();
when compiler sees the new keyword compiler will get an information that it has to allocate memory for a
class object. classname(); will give information to which class the object is to created and how much memory
is to allocated, and initializing the instance variables assigned in constructor also done.
var objectname:classname is similar to var variablename:datatype → here this store the memory location
where the memory allocated for the object. Every object can be identified with some name
Q)what is Reference variable ?
Reference variable is the name given for the object.
Q)what is the purpose of Reference variable ?
The purpose of Reference variable is to access instance variables and instance methods
Every object will have 2 References
1. Default reference variable this(automatically given by compiler to access the instance variables).
2. user defined reference variable
this:- this is a default reference variable given for the object
Q) what is the purpose of this?
The purpose of this is to access instance variables. In Typescript if we want to access instance variables
inside the method or constructor then we have to use this keyword.
Q)what is user defined reference variable? User defined reference variable is the name given for object.
Q)what is the purpose user defined reference variable?
The purpose of user defined reference variable is to access instance methods.
class Student
{ sno:number;
sname:string;
setStudent()
{ this.sno=101;
this.sname="anil";
}
displayStudent()
{ console.log(this.sno);
console.log(this.sname);
}
}
var s1:Student=new Student();
s1.setStudent();
s1.displayStudent();
Constructor
constructor:-constructor is used to initialize the values for variables in Typescript constructor. It must be
declared with constructor keyword. constructor will gets executed when we create object for a class. Separate
call is not required for constructor. It is called special type of setter as it is initializing the instances variables
as soon as the object is created.(Not separate for constructor req).
syntax to declare constructor:-
class classname{ constructor() { } }
Ex:-
class A
{
x:number;
y:number;
z:number;
constructor() {
this.x=10;
this.y=5;
}
getSum() {
this.z=this.x+this.y;
Console.log(this.z);
}
}
var a1:A=new A();
a1.getSum();//instance method
=================================
Parameterised constructor:- At the time of declaring the constructor we have to declare parameters and at
the time creating object we have to pass values through constructor(classname([parameters]))
class A
{ x:number;//x, y and z instance variables
y:number;
z:number;
constructor(a:number,b:number) {
this.x=a;
this.y=b; }
GetSum():void { this.z=this.x+this.y;
console.log(this.z); }
}
var a1:A=new A(6,3);
a1.GetSum();
var a2:A=new A(8,4);
a2.GetSum(); Example when no values initialised to instance variables
Advantages:-
1. Reusability
2. Extensibility
3. Reimplementation
class person {// this is an example for is-a relationship
name:string;
phno:number;
emailid:string;
gender:string;
dob:number;
}
class Student extends person class Employee extends person
{ {
total bsal
per da
grade hra
tsal
} }
Different Types of inheritance:-
1. Single Level inheritance
2. MultiLevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
5. Hybrid inheritance
Single Level inheritance:- creating a derived class (child class) class by using properties and methods from
base class(parent class). It contains only one parent class and one child class.
class A
{ Show() { console.log("i am show"); }
}
class B extends A
{
Disp() { console.log("i am Disp"); }
}
var bhargav:B=new B();
bhargav.Show();
bhargav.Disp();
MultiLevel inheritance:- creating a derived class by using another derived class.
class A
{ Show() { console.log("i am show"); } }
class B extends A
{ Disp() { console.log("i am display");} }
class C extends B
{ Print() { console.log("i am print"); } }
var c1:C=new C();
c1.Show();
c1.Display();
c1.Print();
Hierarchical inheritance:- creating Multiple derived classes by using single base class
class A
{
Show(){ }
}
class B extends A class C extends A class D extends A
{ { {
Disp(){} Print(){ } family(){ }
} } }
var b1:B=new B(); var c1:C=new C(); var d1:D=new D();
b1.Show(); c1.Show(); d1.show();
b1.Disp(); c1.Print(); d1.family();
Overloading:-it is a process of defining multiple methods with same name but with different parameters .in
overloading which methods will gets executed was decided based on the values that we pass
NOTE:
var x:number=”abc”; invalid
var x:any=”abc”; valid
var x:any=10; valid
class {
variables store the value
constructors initialize the values to the instance variables
methods operation
}
object --------->memory allocation for instance variables
this ----------->accessing the instance variables
userdefined Reference ---->accessing the methods
Overriding
Overridding is a process of defining multiple methods with same method heading and with different method
body in base class and derived class
it is a process of Reimplementing the base class method in Derived class
if the base class method is not satisfying the requirement of Derived class then we have to override the base
class in Derived class
Rules to be followed while working with overriding:-
1. inheritance is manadatory
2. same method heading and Different Method body in base class and Derived class
3. Always in Overriding Derived class method will gets executed
class A {
public Show():void { console.log("i am A Show"); } }
class B extends A {
public Show():void { console.log("i am B Show"); }
}
var b1:B=new B();
b1.Show(); o/p:- i am B show
Ex:-
class RBI{ public ROI():void { console.log(3%); } }
class ICICI extends RBI{ public ROI():void{ console.log(5%);} }
class AXIS extends RBI{ public ROI():void{ console.log(7%);} }
class SBI extends RBI{ public ROI():void{ console.log(9%);} }
var r1:RBI=new ----------(); ------------- is object created at runtime by server
var r1:RBI=new ICICI();
r1.ROI(); output:5%
=====================
var i1:ICICI=new ICICI();
==================================================================
class A { }
class B extends A{ }
object :- B
Reference :- B
var b1:B=new B();
===============================================
class A{ }
class B extends A{ } class C extends A{ }
Single Parent-multiple child Exist
object:- Derived class
Reference:- Super class
var a1:A=new ----------();
=======================
class A{}
class B extends A{}
class C extends B{}
object :- C class
Reference :- C class
var c1=new C();
=====================
OverLoading OverRiding
1. it is a process of defyning multiple 1. it is a process of defyning multiple methods
methods with same method name and with same method heading and with
with different parameters is called as different Method body in base class and
Method OverLoading Derived class
2. we can overload operators and methods 2. we can override methods
3.Overloading will exist in single class 3. Overriding is not possible in single class
4. inheritance is optional in overloading 4. inheritance is manadtory in Overriding
5. in Overloading which method 5. in Overriding which method will gets
will gets executed was decided executed was decided based on the object creation
based on the values that we pass
==========================================================================
Interface
Q) Why Interface?
using classes multiple inheritance was not achieved to overcome that interfaces were introduced.
What is multiple Inheritance?
Multiple inheritance means creating a derived class by using multiple base classes
class A{} class B{}
class C extends A,B{} Error
Typescript, c#.net, java doesnot support multiple inheritance by using classes in typescript we can achieve
multiple inheritance by using interfaces
Interface is a typ which consists of abstract methods and variables declarations. By default interface
members are public and abstract.
In TypeScript, you can define an interface by using the keyword interface as below. By default, all the
members in an interface are public, abstract.
interface Person {
fullName: string;
toString(); //method declaration only
}
Once the interface is defined, you can implement it in a class by following this convention: class
[ClassName] implements [InterfaceName]. Let's create two classes
named Employee and Customer implementing the Person interface:
interface Vehicle {
}
interface TwoWheeler extends Vehicle {
}
In TypeScript, an interface can also extend multiple interfaces. For example, let's look at the following code
where the TwoWheeler interface extends the Vehicle and Engine interfaces:
interface Vehicle {
}
interface Engine {
}
interface TwoWheeler extends Vehicle, Engine {
}
class Vehicle {
constructor (public brand: string) { }
getBrandName() {
return brand;
}
}
class Engine {
constructor (public manufacturer: string) { }
getManufacturerName() {
return manufacturer;
}
}
interface TwoWheeler extends Vehicle, Engine {
getBrandName();
getManufacturerName()
}
In other words, you can create an interface that extends a class and then it can be implemented in another
class or interface.
interface is a type which consists of public abstract members .By default interface members are public and
abstract. interface will provide some set of specifications and these specifications must implement in the
Derived class. interface members must implement in derived class, interface doesn’t have any
implementations (No Method body)
interface implementations must define in derived class
class { interface{ abstract class{
variables abstract methods; concrete methods
concrete methods variable declarations Abstract methods
} } }
Interface can be implemented in another class
concrete method:- Method having body is called as concrete method
concrete method is also called as implemented method
class A{
Show():void {
--------------
--------------
}
}
abstract method:-Method without body is called as abstract method.abstract method is also called as
unimplemented method.we can declare abstract methods in interface or abstract classes. interface members
must implement in Derived class.we cannot create object for interface .but we can create Reference for
interface.
syn:-interface interfacename{ }
class classname implements interfacename{ }
class A { } abstract class A{ } interface A{ } interface A{ }
class B extends A{ } class B extends A{ } class B implements A{ } interface B extends A{ }
A class can extend another class, A class must implement interface
interface A interface B
{ Show():void;} {Disp():void;}
class B implements A,B{
Show():void { console.log("i am show"); }
Disp():void { console.log("i am Display"); }
}
var b1:B=new B();
b1.Show();
Q)can we create object for interface ? no we cannot create object for interface but we create reference
Q)why we cannot create object for interface?
interface consists of unimplemented methods(method without body)
Q)can we create reference for interface? yes we can create reference
Q)what methods we can access with interface reference?
with interface reference we can access the implemented methods in the derived class
note:- Always interface and abstract class was declared as super class
Q)in what scenario we have to declare super class reference?
in the scenario where single parent and multiple child exists then we have to declare super class Reference
interface Shape {Draw():void; }
class Square implements Shape{ class Rectangle implements Shape {
Draw():void { console.log("Draw a square");} } Draw():void{console.log("Draw a Rectangle");} }
var s1:Shape=new ------();
interface IDbConnection {
Open():void;
Close():void;
}
class Oracle implements IDbConnection{ class MySQL implements IDbConnection{
Open():void {code to connect to oracle DB} Open():void{code to connect to MYSQL DB}
Close():void { } } Close():void { } }
interface is used to achieve multiple Inheritance .multiple Inheritance means creating a derived class by using
multiple base classes.Typescript doesnot support multiple inheritance by using classes.we can achive multiple
inheritance by using interfaces .
Q)why Typescript doesnot support Doesnot support multiple inheritance by using classes?
class A{ class B {
Show():void{ Iam A show} Show():void{ Iam B show}
} }
class C extends A,B { } //This program will not working typescript
observation:- in the above program same method exist in both the base classes ,because of inheritance these
2 methods are available in Derived class with derived class object and Reference if we access Show() then an
ambiguity problem will occur that which method must gets executed. inorder to overcome the above ambiguity
problem Typescript doesnot support multiple inheritance by using classes
interface A{ Show():void;} interface B{ Show():void;}
class C implements A,B{ }
note:- a class can extend only one class, but a class can implement multiple interfaces
Tightly coupling:- creating object for one class inside another class by using new keyword then we can say
that both the classes are Tightly coupled with each other .classes and objects are dependent on each other
class A{ }
class B { A a1=new A();
Get():void { A a2=new A(); } }
class Square{ class Shape{
Draw():void{ console.log("Draw a square"); } } GetShape():void{
class Rectangle { var s1:Square=new Square();
Draw():void{ console.log("Draw a Rectangle"); } } s1.Draw();
class Triangle { var r1:Rectangle=new Rectangle();
Draw():void{ console.log("Draw a Triangle"); } } r1.Draw();
var t1:Triangle=new Traingle(); t1.Draw(); }
var s1:Shape=new Shape(); }
s1.GetShape();
Loosly coupling:-Loosly coupling means decrease the degree of dependencies between the classes. we can
achive Loosly coup[ling by using interfaces. in Loosly coupling Mechanism we must not directly create object
for one class inside another class by using new keyword.
interface Ishape{ Draw():void; }
class Shape { GetShape(Ishape is):void{ is.Draw();}}
var s1:Shape=new Shape();
s1.GetShape(new Square());
class Square implemets IShape{ Draw():void { console.log("Draw a square"); } }
class Rectangle implements IShape{ Draw():void { console.log("Draw a Rectangle"); } }
class Triangle implements IShape{ Draw():void { console.log("Draw a Triangle"); } }
Method:- Method is a subprogram which is used to perform some operation
Method will have parameters and return type
Datatypes are of 2 Types:-Primitive (number and String), Reference type(class , interface, arrays)
Method will have Parameters:-
The no of, order of, type of values that we pass must match with no of, order of type of parameters if the
parameter of the method is primitive type then at the time of calling the method we have to pass values
class A {
Show(x:number):void { console.log(x); }
}
var a1:A=new A();
a1.Show(6);
if the i/p parameter of the method is class then at the time of calling the method we have to pass object
or Reference
class A { Show():void { console.log("i am show"); } }
class B{ Get(A a1):void { a1.Show(); } }
var b1:B=new B();
b1.Get(new A());
if the i/p parameter of the method is super class then then at the time of calling the method we have to pass
derived class object
class A{ Show(){ }}
class B extends A{ } class C extends A{ } class D extends A{ }
class X{ Get(A a1):void { } }
var x1:X=new X();
x1.Get(new B());
=================================================================
if the i/p parameter of the method is interface then then at the time of calling the method we have to pass
derived class object
=============================================
object Reference Example
single parent- single child child child child c=new child();
single parent -mutiple child child create at runtime parent parent p=new -------();
interface--multiple childs child create at runtime parent parent p=new -------();
Abstract Classes
interface IStudent {
stdname:string;
sno:number;
}
function GetStudent(s:IStudent){ console.log("sname is"+s.stdname+" "+"sno is "+s.sno);}
GetStudent({stdname:"Anil",sno:101});
interfaces:-interface is a type which consists of public abstract methods and variables
interface methods must implement in Derived class
By using interfaces we can achive Multiple Inheritance
By using interfaces we can achive Loosly coupling
interface is a contract or an aggrement between itself and its implemented class i.e interface will provide some
set of specifications and these specifications must impelment in derive class
abstract class:- abstract class must declare with abstract keyword
abstract class consists of concrete methods and abstract methods
concrete method :- method with body is called as concrete method
concrete method is implemented method
abstract method:- method without body is called as abstract method
abstract method is unimplemented metho
abstract method must implement in derived class
class interface abstract class
{ { {
variables declare variables variables
concrete methods abstract methods concrete methods
constructors } abstract methods
static methods constructors
} static methods
}
we cannot create object for abstract class or interface
but we can create reference
Ex:-abstract class A
{ public abstract Show():void;
public Display():void { console.log("i am Display") }
}
class B extends A{ public Show():void { console.log("i am show"); } }
var b1:B=new B();
b1.Show();
b1.Display();
Ex:- interface Icar {
price():number;
CompanyName():string;
Model():string;
}
abstract class Maruti implements Icar {
abstract price():number;
abstract Model():string;
CompanyName():string {
return "Martuti";
}
}
class Dzire extends Maruti class Wagonar extends Maruti
{ {
price():number{ return 10,00,000; } price():number{ return 6,00,000; }
Model():string{ return "LXI"; Model():string{ return "VXI"; }
} }
ANGULAR
Q) What is Angular?
Angular is open source and front end based web development platform, which perform best when used for
building dynamic ,SPA (Single Page Application) , developed and maintained by GOOGLE.
Angular was developed by using Typescript language. We can create web application that run on Multiple
Devices. Angular is not a developed version of AngularJS, Angular was completely rewritten by using
Typescript language.
Angular Versions(Misko Hevery)
JavaScript → Browser
JQuery→ Library
Typescript → Programming Language (Microsoft)
AngularJS → Client side Java script Framework (Google) by using MVC Design pattern.
Angular 2/4/5/6/7/8/9 → TypeScript Framework (Google) by using Component Architecture(MVT)
Difference between AngularJS and Angular
AngularJS Angular
Author Google Google
Architecture MVC Framework Component Based
Language JavaScript Typescript
Rendering Client Side Server Side
Data Binding BiDirectional BiDirectional
Latest Version Angular 1.7 Angular 9
It uses Controller and scope It uses Component and Directives
Setup Setup is not difficult Setup is difficult
Casing It doesn’t use camel case for build in It uses camel case for build in Directives
Directives like ng-model like ngModel
Dependency Dependency Injection achieved via Dependency Injection achieved via
Injection Controller Constructor
Mobile support No Yes
What is Module?
• Module in angular refers to a place where you can group the components, directives, pipes, and
services, which are related to the application.
• Every Angular application has atleast one module which is root module and by convention it is
AppModule and it resides inside app.module.ts
Modules in Angular
• Angular Modules are used to group components,directives,pipes,services that are related to a particular
group of angular appn
• Angular apps are modular and to maintain modularity, we have Angular modules or you can
say NgModules.
• Every Angular app contains at least one Angular module, i.e. the root module. Generally, it is named
as AppModule.
• The root module can be the only module in a small application.
• in some applications we have multiple modules. Any angular module is a class with @NgModule
decorator.
Decorators
Decorators are basically used for attaching metadata to classes so that, it knows the configuration of those
classes and how they should work. NgModule is a decorator function that takes metadata objects whose
properties describe the module.
• declarations: The classes that are related to views and they belong to this module. There are three
classes of Angular that can contain view: components, directives, and pipes. We will talk about them
in a while.
• exports: The classes that should be accessible to the components of other modules.
• imports: Modules whose classes are needed by the component of this module.
• providers: Services present in one of the modules which are to be used in the other modules or
components. Once a service is included in the providers it becomes accessible in all parts of that
application
• bootstrap: The root component which is the main view of the application. This root module only has
this property and it indicates the component that is to be bootstrapped
• assets folder
Where we can store static assets of our application for example images, icons etc.
• environment folder
Where we can store configuration settings for different environments. Basically, this folder contains
two files,
– environment.prod.ts file for the production environment.
– Environment.ts file for the development environment.
• index.html file contains our Angular application. Here, you can not find any reference to CSS or other
JS files. All other pages are dynamically inserted into the page.
• main.ts file is a TypeScript file. It is the starting point of our application. Here, we can bootstrap (the
process of initializing or loading) our main module using bootstrapModule method like,
• platformBrowserDynamic().bootstrapModule(AppModule);
• style.css is where we can add global styles for our applications.
• angular-cli.json is standard configuration file of your application
• polyfiles.ts: to make our application run on old browser related information is kept here.
• Karma.conf.js file is used to store the setting of Karma i.e. test cases.
• package.json file is a standard file. Every node and Angular project contain this file. Basically, this
file contains all information like name of the project, versions information, dependencies and dev-
dependencies settings.
• tsconfig.json file has a bunch of settings for your TypeScript compiler, so your typescript compiler
looks at the setting and based on these settings, compile your typescript code into javascript, so that
browser can understand.
• Note:Module, Component, Services are all classes
• Module Component Services
• class{ } class{} class{ }
•
•
• A Component needs to have a view. To define a view, you can define a template.
• A template is a form of HTML that tells angular how to render the component.
•
•
•
• import { Component } from '@angular/core';
@Component({
• selector: 'app-root,
• templateUrl: ‘’,
• styleUrls: [‘’]
• })
• export class AboutComponent {
• constructor() { }
• ngOnInit() {
• }
}
•
•
•
• @Component({
• selector: 'app-root',
• template: '<h1> Welcome to Angular </h1>',
• styleUrls: ['./app.component.css']
• })
• import { Component } from '@angular/core';
@Component({
• selector: 'app-root',
• template: "<h1> Welcome to Angular </h1>",
• styleUrls: ['./app.component.css']
• })
• export class AppComponent {
• title = 'cp';
• }
• import { Component } from '@angular/core';
@Component({
• selector: 'app-root',
• template: `<h1>
• Welcome to Angular
• </h1>`,
• styleUrls: ['./app.component.css']
• })
• export class AppComponent {
• title = 'cp';
• }
• import { Component } from '@angular/core';
•
@Component({
• selector: 'app-root',
• templateUrl: './app.component.html',
• styleUrls: ['./app.component.css']
• })
• export class AppComponent {
• title = 'cp';
• }
• Execution Flow of Angular project
• ng serve -o
• main.ts will gets executed
• main.ts will search for RootModule(AppModule)
• app.module.ts will gets executed
• bootstrap---->will load AppComponent
• app.component.ts will execute
• @Component({
• selector: 'app-root',
• templateUrl: './app.component.html',
• styleUrls: ['./app.component.css']
• })
• app.component.html will execute and the o/p will render with app-root of index.html and display
index.html o/p in Browser
•
•
• 1. command to check nodejs installation
• node -v
• 2. command to check npm installation
• npm -v
• 3. command to check typescript installation
• tsc -v
• 4. command to check angular installation
• ng v
• 5. command to create angular project
• ng new projectname
• Ex:- ng new myproject
• 6. command to create angular module
• ng g m modulename
• Ex:- ng g m student
• 7. command to create angular component
• ng g c componentname
• Ex:- ng g c home
• 8. command to create angular service
• ng g s servicename
• Ex:- ng g s login
• 9. command to run angular project
• ng serve -o
• whenever we run ng serve -o command then node.js run the angular project
Creating Angular Project
1. goto----> F Drive and create a folder with name Ag7AM
2. open node.js command prompt
3. change the Drive D:
4. change the Directory: cd ag7am
5. create angular project
ng new projectname
ng new sampleproject
6. open visualstudiocode and open folder : F:\Ag7am\sampleproject
7. goto--->terminal--->newterminal F:\Ag7am\sampleproject> ng serve –o
Angular is a Single page application. i.e Whenever we click on link desired page will come without
refreshing page.
Output on running the basic Project with out adding any code to project created.
By replacing All code present in app.component.html with below code to print ”Hello Welcome to
Angular”
Create a project which take fname, lname from user and print the full name.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent, ],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
ngModel: it is used to catch the value entered at runtime on the html page text box.
Enter FirstName<input type="text" [(ngModel)]="FirstName"><br>
Enter LastName<input type="text" [(ngModel)]="LastName"><br>
<input type="button" (click)="GetFullName()" value="Display"><br>
<span>{{FullName}}</span>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
FirstName:string;
LastName:string;
FullName:string;
public GetFullName():void
{
this.FullName=this.FirstName+this.LastName; }
title = 'cp';
}
Output:
Tasks:
Task1: Create a project to display Da,Hra,Tsal based on the Basic Salary entered by the user.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent, ],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
Enter Eno <input type="number" [(ngModel)]="Eno"><br>
Enter Ename <input type="string" [(ngModel)]="Ename"><br>
Enter BSalary <input type="number" [(ngModel)]="BSalary"><br>
<input type="button" (click)="Display()" value="Display"><br>
<span>Da is: {{Da}} </span><br>
<span>Hra is: {{Hra}} </span><br>
<span>Tsal is: {{Tsal}} </span><br>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
Eno:number;
Ename:string;
BSalary:number;
Da:number;
Hra:number;
Tsal:number;
public Display(){
this.Da=(10/100)*this.BSalary;
this.Hra=(8/100)*this.BSalary;
this.Tsal=this.BSalary+this.Da+this.Hra;
}
title = 'employeesalary';
}
Output:
Task2: Create a project to display Total, Percentage,Grade based on the 3 different marks entered by
the user.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent, ],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
Sno:number;
M1:number;
M 2:number;
M3:number;
Total:number;
Percentage:number;
public Display(){
this.Total=this.M1+this.M2+this.M3;
this.Percentage=this.Total/3;
}
title = 'Studentdetails';
}
app.component.html
Enter Sno <input type="number" [(ngModel)]="Sno"><br>
Enter M1 <input type="number" [(ngModel)]="M1"><br>
Enter M2 <input type="number" [(ngModel)]="M2"><br>
Enter M3 <input type="number" [(ngModel)]="M3"><br>
<input type="button" (click)="Display()" value="Display"><br>
<span>Total is: {{Total}} </span><br>
<span>Percentage is: {{Percentage}} </span><br>
<router-outlet></router-outlet>
Output:
• In the normal HTML site, we use like <a href="about.html">About</a> but here instered of that, we
going to use Angular route concept with routerLinkActive, like this <a routerLink="about"
routerLinkActive="active">About</a>
• Once you completed all the steps now run the command ng serve --open and see the output with
an active link. For your reference below you have the output how it looks like.
OUTPUT:
Directives
Q) What is Directives?
Directives are one of the important and cool feature of angular application and its play a important role in
angular projects. With the help of directive we can easily manipulate our DOM layout.
<div hidden> </div>
<p hidden ></p>
ngIf else
To begin with, Angular 9/8/7 Ngif works like regular if else only. It will evaluate the expression and it will show or
hide the element based on the result of that evaluation.
You need to know that Ngif basic syntax is effective and simple. Here you need to prefix an asterisk (*) with the
directive name. Then you can include it inside the template, wherever you wish to have it. Well, we are definitely
going to address why use an asterisk as we explore ngIf in Angular.
// * + ngIf = *ngIf Directive formula
As far as using *ngIf is concerned, there are 4 main ways. We will start with the basic form first below:
1st way:
app.
@Component({
selector: 'my-app',
template: ` <div *ngIf="userLoggedIn">
Hello <strong>User</strong> </div> `,
})
export class AppComponent {
userLoggedIn = true;
}
Output:
2nd way: Using Logical NOT (!) Operator with NgIf in Angular
@Component({
selector: 'my-app',
template: ` <div *ngIf="!userLoggedIn">
Login, <strong>user</strong> </div> `,
})
export class AppComponent {
userLoggedIn = false;
}
Output:
3rd way:Using Logical AND (&&) Operator with Angular NgIf. Check out the && operator example in Angular
with *ngIf.
@Component({
selector: 'my-app',
template: ` <input type="checkbox" [(ngModel)]="checked"/>
<input type="checkbox" [(ngModel)]="checked2" />
<span *ngIf="checked && checked2">
Show this text when both checkboxes are checked! </span>`,
})
export class AppComponent {
alert('Check both the checkboxes to show message')
}
4th Way:
Using Logical OR (||) Operator with Angular NgIf
Check out the || operator example in Angular with *ngIf.
@Component({
selector: 'my-app',
template: ` <div *ngIf="x == 5 || y == 5">
Angular Logical || Testing </div> `,
})
export class AppComponent {
x = 5;
y = 9;
}
Output;
Else statement is an excellent addition to Angular 9/8/7. It has its roots in Angular JS. There is nothing
complicated about this though. If this, execute this else execute something else.
@Component({
selector: 'my-app',
template: ` <div *ngIf="userLoggedIn; else userloggedOut">
Hello User
</div>
<ng-template #userloggedOut>
Hello User, Login
</ng-template> `,
})
Here the thinking in the flow of statements has been accustomed to the syntax. It aligns well with our thoughts, like
this:
ngIf = condition ? then : else;
app.component.ts:-
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myd';
X:number;
visible:boolean=false;
CheckEven()
{
this.visible=this.X%2==0;
}
}
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
Enter a no
<input type="number" [(ngModel)]="X"><br>
<input type="button" (click)="CheckEven()" value="Check"/>
<div *ngIf="visible;then Even else Odd"></div>
<ng-template #Even>Even no</ng-template>
<ng-template #Odd>Odd no</ng-template>
<router-outlet></router-outlet>
Output:
Example 1: Write a project to validate the username and password of login page?
Step 1: Install the Angular project.
Before Routing first, you need to install the Angular project for that use the below command to create your
new Angular project.
ng new router (project name)
Step 2: Create new three components in your Angular app.
Now create a new three components as home, about, contact in your Angular app. Follow the below
commands which help you to create components.
ng g c home
ng g c about
ng g c contact
ng g c login
Step 3: Import created three components.
Import created three components inside the src >> app >> app.module.ts Below you have the code use like
as same. Also the router needs a <base href="/"> to be set in the index.html section.
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { LoginComponent } from './login/login.component';
import {from} from 'rxjs';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
ContactComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4: Configure routing in your app-routing.module.ts
Now setup routes path in your src >> app >> app-routing.module.ts as like the below code.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './home/home.component';
import{AboutComponent} from './about/about.component';
import{ContactComponent} from './contact/contact.component';
import {LoginComponent} from './login/login.component';
const routes: Routes = [
{path:"",component:HomeComponent},
{path:'home',component:HomeComponent},
{path:'about',component:AboutComponent},
{path:'contact',component:ContactComponent},
{path:'login',component:LoginComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Above you can see, we define the created component routes path and path name with
the component and component name.
Step 5: Define the Router with active links
Now open and add the routerLink in your app.component.html as like the below.
<div>
<h1>
Welcome to {{title}}!
</h1>
</div>
<ul>
<li>
<a routerLink="home" routerLinkActive="active">Home</a>
</li>
<li>
<a routerLink="login" routerLinkActive="active">Login</a>
</li>
<li>
<a routerLink="contact" routerLinkActive="active">Contact</a>
</li>
<li>
<a routerLink="about" routerLinkActive="active">About</a>
</li>
</ul>
<router-outlet></router-outlet>
home.component.html
<p>Welcome to Home Page!</p>
about.component.html
<p>Welcome to About Page!</p>
contact.component.html
<p>Welcome to Contact Page!</p>
login.component.html
<p>Welcome to Login Page!</p>
<div>
Enter UserName <input type="text" [(ngModel)]="UserName"><br>
Enter Password <input type="password" [(ngModel)]="Password"><br>
<input type="button" value="Signin" (click)="CheckUser()"><br>
<div *ngIf="isvalid">Valid user</div>
<div *ngIf="isinvalid">inValid user</div>
</div>
Login.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
UserName:string;
Password:string;
isvalid:boolean;
isinvalid:boolean;
constructor() { }
ngOnInit(): void { }
CheckUser(){
if(this.UserName=="Admin" && this.Password=="Admin"){
this.isvalid=true;
this.isinvalid=false;
}
else{
this.isvalid=false;
this.isinvalid=true;
}
}
}
<table>
<tr>
<th>Eid</th>
<th>Ename</th>
<th>ESalary</th>
<th>eage</th>
</tr>
<tr *ngFor="let employee of Employee">
<td>{{employee.id}}</td>
<td> {{employee.employee_name}} </td>
<td> {{employee.employee_salary}} </td>
<td> {{employee.employee_age}} </td>
<td> {{employee.profile_image}} </td>
</tr>
</table>
Output:
What is the ngFor directive scope?
When we are working with the ngFor directive, we should also be aware of its scope.
The variable we use to display the data with ngFor is only available to its scope. It similarly works the way other
method works to iterate over a data collection in different programming languages.
For example, this will be a valid syntax:
<ul>
<li *ngFor="let employee of Employee ">
<h3>{{employee.id}}</h3>
<p> {{employee.employee_name}} </p>
</li>
</ul>
Output : like this all will be printed.
1.Write a project to display data in table format with out using SERVICES??
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myd';
users:any[]=[
{eno:101,ename:"anil",salary:20000},
{eno:102,ename:"sunil",salary:30000},
{eno:103,ename:"ajay",salary:25000},
{eno:104,ename:"vijay",salary:40000}
];
}
app.component.html
Welcome
<div>
<table>
<tr>
<th>Eno</th>
<th>Ename</th>
<th>Salary</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.eno}}</td>
<td>{{user.ename}}</td>
<td>{{user.salary}}</td>
</tr>
</table>
</div>
<router-outlet></router-outlet>
Output:
Directives Description
ngSwitch It’s a structural directive, all the possible values defined inside of it. It gets the
switch value based on the matched statement among multiple possibilities.
ngSwitchCase The ngSwitchCase statement is declared inside the ngSwitch directive with the
specific value.
ngSwitchDefault This statement executes when the expression doesn’t match with any of the
defined value.
Services
Sharing of data is one of the requirement in angular application. Sometimes we want to use same data
across components. So to do so you have 2 approaches
1. create that data in each component individually - but there is drawback with that approach we
are re-writing the code which is against the approach of DRY(DONT REPEAT YOURSELF)
and code also become lengthy , complex and less testable. So next approach is Services.
Services follows singleton object.
ng serve -o
main.ts class will be loaded ---->search for RootModule (AppModule)
app.module.ts:-
@NgModule({
declarations:[], register components
imports:[], register imported modules
providers:[UserService], register services
bootstrap:[AppComponent], default componentname
})
export class AppModule{ }
object is created for UserService by angular Framework and this object is singleton object. singleton
object means single instance(object) was created for the class and this object is consumed in multiple
components,object is created for AppComponent. whenever object is created then constructor() will gets
invoked, here we need to pass the userservice as parameter to AppComponent constructor.
class AppComponent implements OnInit{
constructor(private us:userservice) { }
ngOnInit(){}
}
in Angular constructors are used to inject the service objects within the components
ngOnInit() :- it is the implemented method of OnInit interface
it is the Angular Lifecycle Hook method
This method will invoke automatically after executing the constructor
within ngOnInt() we are invoking the service method getAllUsers()
and we are assigning the result of the method to users variable
and finally the o/p will be rendered with Html Table of app.component.html
and finally <app-root> index.html
1.Write a project to display data in table format using SERVICES??
users.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor() { }
getAllUsers()
{
return [
{eno:101,ename:"anil",salary:20000},
{eno:102,ename:"sunil",salary:30000},
{eno:103,ename:"ajay",salary:25000},
{eno:104,ename:"vijay",salary:40000}
];
}
}
Register service in app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {UsersService} from './services/users.service';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component, OnInit } from '@angular/core';
import { UsersService } from './services/users.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'myd'; //titleof project
constructor(private userservice:UsersService) { }
ngOnInit()
{ this.users=this.userservice.getAllUsers(); }
users:any[];
}
Output:
Most front end applications communicate with backend services over HTTP protocol. HTTP services is
the important part of any application which communicates with server.
Stateless Management: every time when the method is called amount is reinitialized with 0.
Httpclient methods
post: insert data, put: update data, delete: delete data
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private httpservice:HttpClient) { }
getAllUsers() { return this.httpservice.get("http://jsonplaceholder.typicode.com/users"); }
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { UsersService } from './services/users.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'myd';
users:any;
constructor(private userservice:UsersService)
{
}
ngOnInit()
{
this.userservice.getAllUsers().subscribe((data)=>
{
this.users=data;
});
}
}
app.component.html
<div>
<table>
<tr>
<th>Name</th>
<th>UserName</th>
<th>email</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
</table>
</div>
<router-outlet></router-outlet>
Output:
Features of JSON:
• It is light-weight
• It is language independent
• Easy to read and write
• Text based, human readable data exchange format
• <students> <student> <name>John</name> <age>23</age> <city>Agra</city> </student>
<student> <name>Steve</name> <age>28</age> <city>Delhi</city> </student> <student>
<name>Peter</name> <age>32</age> <city>Chennai</city> </student> <student>
<name>Chaitanya</name> <age>28</age> <city>Bangalore</city> </student> </students>
• {"students":
[
{"name":"John", "age":"23", "city":"Agra"}, {"name":"Steve", "age":"28", "city":"Delhi"},
{"name":"Peter", "age":"32", city":"Chennai"}, {"name":"Chaitanya", "age":"28",city":"Ban"}
]
}
JSON data structure types and how to read them:
• JSON objects
• JSON objects in array
• Nesting of JSON objects
JSON objects
var emp=
{
"name" : "Chaitanya Singh",
"age" : "28",
"website" : "beginnersbook“
};
JSON objects in array
• In the above example we have stored the information of one person in a JSON object suppose we
want to store the information of more than one person; in that case we can have an array of objects.
var students =
[ { "name" : "Steve", "age" : "29", "gender" : "male" },
{ "name" : "Peter", "age" : "32", "gender" : "male" },
{ "name" : "Sophie", "age" : "27", "gender" : "female" } ];
To access the information out of this array, we do write the code like this:
document.writeln(students[0].age); //output would be: 29 document.writeln(students[2].name); //output:
Sophie
Nesting of JSON objects:
another way of doing the same thing that we have done above.
var students =
{ "steve" : { "name" : "Steve", "age" : "29", "gender" : "male" },
"pete" : { "name" : "Peter", "age" : "32", "gender" : "male" },
"sop" : { "name" : "Sophie", "age" : "27", "gender" : "female" } }
document.writln(students.steve.age);
//output: 29 document.writeln(students.sop.gender); //output: female
How to read data from json file and convert it into a JavaScript object?
We have two ways to do this.
1) Using eval function, but this is not suggested due to security reasons (malicious data can be sent from
the server to the client and then eval in the client script with harmful effects).
2) Using JSON parser: No security issues plus it is faster than eval. Here is how to use it:
• var emp= { "name" : "Chaitanya Singh", "age" : "28", "website" : "beginnersbook" };
• We are converting the above JSON object to javascript object using JSON parser:
• var myJSObject = JSON.parse(emp);
Create a project to demonstrate the working of json server with an login page??
Index.html:-
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<table>
<tr>
<td>
<img src="./assets/1a.png" height="70" width="300">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<app-root></app-root>
</td>
</tr>
<tr>
<td></td>
</tr>
</table>
</body>
</html>
app.module.ts:-
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ContactComponent } from './contact/contact.component';
import { LoginComponent } from './login/login.component';
import { LoginService } from './login.service';
import {HttpClient,HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutusComponent,
ContactComponent,
LoginComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [LoginService],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts:-
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit{
title = 'jsonlogin';
UserName:string;
Password:string;
IsValid:boolean;
IsInValid:boolean;
ngOnInit(){ }
OnSubmit() {
if(this.UserName=="Admin" && this.Password=="Admin")
{
this.IsValid=true;
this.IsInValid=false;
}
else
{
this.IsInValid=true;
this.IsValid=false;
}
}
}
login.component.html:-
<div>
Enter UserName <input type="text" [(ngModel)]="UserName"> <br>
Enter Password
<input type="password" [(ngModel)]="Password">
<br>
<button (click)="OnSubmit()">Signin</button>
<span *ngIf="IsValid">
Valid User
</span>
<span *ngIf="IsInValid">
InValid User
</span>
</div>
db.json:-
{
"login": [
{
"username": "Admin",
"password": "Admin"
}
]
}
This has to be run ( json-server –watch db.json) and then run the angular project.
Debugging
Fn+f12→ Inspect
F8→ directly goto debugger
F10 or f11 → move to next line
Create a project with name empdetailseditdel to store data in json server as user enters in reg form
and to perform updation, deletion of data as per requirement?
1. create register component: ng g c register
2. create a service: ng g s register
3. install json server: npm install -g json-server
4. start json server: json-server --watch db.json
5. edit db.json
{
"emp": [
{
"id": 101,
"ename": "anil",
"salary": 20000
},
{
"id": 102,
"ename": "sunil",
"salary": 20000
},
{
"id": 103,
"ename": "sujith",
"salary": 25000
},
{
"id": 104,
"ename": "vijtha",
"salary": 45000
},
{
"id": 105,
"ename": "Bhargav",
"salary": 75000
}
]
}
code for app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RegisterComponent } from './register/register.component';
import {FormsModule} from '@angular/forms';
import {RegisterService} from './register.service';
import { from } from 'rxjs';
import{HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
RegisterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [RegisterService],
bootstrap: [AppComponent]
})
export class AppModule { }
code for app.component.html
<app-register></app-register>
<router-outlet></router-outlet>
Pipes or Filters
Angular JS 1.x has filters which are used for many common uses like formatting dates, string display in
uppercase or lowercase etc. These filters are knows as "Pipes" in Angular
Pipes allows us to change the data before display to the user.
Normally a pipe takes the data and transforms this input to the desired output. There are two types of pipes
in Angular
1) built-in pipes
2) Custom pipes
Built in pipes are already created in angular ,we just need to call that if we want to use it. If Built-in pipes
are not sufficient for project needs we are free to create custom pipes
There are 10 built in pipes in angular
1) Uppercase
2)Lowercase
3)Titlecase
4)date
5)Currency
6)Number
7)date
8)slice
9)json
10)async
Syntax : {{ expression | pipename:arguments }}
Whenever you want to use pipe just use pipe name followed by pipe(|) character. Pipes are methods behind
the scene , so methods can take arguments in same manner pipe can also take argument which you will pass
after colon(:)
Chaining of Pipe: Sometime we want to use more than one pipe on same expression so this is called
chaining of pipe. So here suppose we want to apply date and uppercase together on dob express
{{dob | date | uppercase}}
In this case output of date pipe will act like a input for uppercase pipe
Pipes in Angular:-
Pipes (|) in Angular are used to transform the data before displaying it in a browser. Angular provides a lot
of built-in pipes to translate the data before displaying it into the browser
Angular lets us extend its features we can even create custom pipes in Angular. So in this article, we are
going to learn the built-in pipes which are provided by Angular
Pipes can be applied to:-
• Pipes which we can apply to Strings
• Pipes which we can apply to Numbers
• Pipes which we can apply to Date
Pipes which we can apply to String
• Uppercase - We can use this pipe to convert the data-bound expression to uppercase.
• Lowercase - We can use this pipe to convert the data-bound expression to lowercase.
• Slice – We can use this pipe to extract the substring from the data-bound expression. This pipe takes
two parameters - starting index of a string and the last index of the string.
• Titlecase: Pipes which we can apply to Numbers. We can use these pipes to format the numbers
• Number – We can use this pipe to convert the number to a different format.
• Currency – We can use this pipe to show currency symbol. This pipe takes two parameters -
currency i.e USD, EURO, and GTP; and the Boolean value which decides whether we want to display the
currency symbol or not. See the below code and output screenshot for more information.
NOTE: Filters or pipes are used to format the output before displaying on th browser.
Example 1:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'pipedemo';
public Sno:number=12345;
public Sname:string="anilkumar";
public Cname:string="SQLSERVER";
public Emailid:string="[email protected]";
public JoinDate:Date=new Date();
public Fees:number=4500;
public CollegeName:string="sathyatechnologies";
}
app.component.html:-
<div>
StudentNo is{{Sno}} <br>
StudentName {{Sname|uppercase}}<br>
Cname is{{Cname|lowercase}}<br>
Emailid is{{Emailid}}<br>
DateofJoin {{JoinDate}}<br>
DateofJoin {{JoinDate| date:'shortDate'}}<br>
DateofJoin {{JoinDate| date:'longDate'}}<br>
DateofJoin {{JoinDate| date:'mediumDate'}}<br>
Course Fees {{Fees|currency:'USD':true}}<br>
Course Fees {{Fees|currency:'EUR':true}}<br>
CollegeName is{{CollegeName|slice: 0: 6}}<br>
CollegeName is{{CollegeName|slice: 6: 10}}
</div>
<router-outlet></router-outlet>
Output:
Example 2:
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'myp';
users:any[]=[
{id:101,name:'Anil',city:'HYDERABAD',salary:100,dob:new Date("09/02/1982")},
{id:102,name:'Sunil',city:'HYDERABAD',salary:10000,dob:new Date("03/02/1985")},
{id:103,name:'Ajay',city:'VIZAG',salary:20000,dob:new Date("09/12/1990")},
{id:104,name:'Vijay',city:'PUNE',salary:40000,dob:new Date("03/02/1987")},
{id:105,name:'John',city:'Banglore',salary:500,dob:new Date("06/03/1999")},
];
}
app.component.html
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>City</th>
<th>Salary</th>
<th>Salary</th>
<th>Salary</th>
<th>Salary</th>
<th>Salary</th>
<th>Salary</th>
<th>Dob</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.name|uppercase}}</td>
<td>{{user.city|lowercase}}</td>
<td>{{user.salary|currency}}</td>
<td>{{user.salary|currency:'INR':'code'}}</td>
<td>{{user.salary|currency:'INR':'symbol':'3.3'}}</td>
<td>{{user.salary|currency:'INR'}}</td>
<td>{{user.salary|currency:'USD':'symbol':'3.3'}}</td>
<td>{{user.salary|currency:'EURO':'symbol':'3.3'}}</td>
<td>{{user.dob|date:'dd/MM/yyyy'}}</td>
</tr>
</table>
<pre>
{{users|json}}
</pre>
<router-outlet></router-outlet>
Output:
custom pipes:- The pipes that was created by the programmer depending on the user requirement are
called as ciustom pipes
syn to create pipe:-
ng g p pipes/pipename
ex:ng g p pipes/age
create a project to display age based on dob given by user.
1. Create a pipe with name age
ng g p pipes/age
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgePipe } from './pipes/age.pipe';
@NgModule({
declarations: [
AppComponent,
AgePipe
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'userloginngif';
users:any[]=[
{id:101,name:'Anil',city:'HYDERABAD',salary:100,dob:new Date("09/02/1982")},
{id:102,name:'Sunil',city:'HYDERABAD',salary:10000,dob:new Date("03/02/1985")},
{id:103,name:'Ajay',city:'VIZAG',salary:20000,dob:new Date("09/12/1990")},
{id:104,name:'Vijay',city:'PUNE',salary:40000,dob:new Date("03/02/1987")},
{id:105,name:'John',city:'Banglore',salary:500,dob:new Date("06/03/1999")},
];
}
App.component.html
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>City</th>
<th>Salary</th>
<th>Salary</th>
<th>Dob</th>
<th>Age</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.name|uppercase}}</td>
<td>{{user.city|lowercase}}</td>
<td>{{user.salary|currency:'INR':'code'}}</td>
<td>{{user.salary|currency:'INR':'symbol':'3.3'}}</td>
<td>{{user.dob|date:'dd/MM/yyyy'}}</td>
<td>{{user.dob|age}}</td>
</tr>
</table>
<pre>
{{users|json}}
</pre>
<router-outlet></router-outlet>
<router-outlet></router-outlet>
age.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'age'
})
export class AgePipe implements PipeTransform {
}
Output:
Angular Forms
Formtags:-
Redirection,Validation,submissions,Reset,Clear
Prerequisites:-
1. HTML
2. Javascript
3. CSS
4. Angular Components,Services,Templates,Databinding
Forms can be difficult to style. Not only do form elements display differently in different browsers, but most
browsers limit the visual changes you can make to form controls.
2.Reactive Forms (Model Driven Approach): Most of the code written in component class.
Template-driven Forms Reactive Forms
Easy to use More flexible→More Complex scenaries
Similar to angular 1 Immutable data model
Two way data binding→Minimal Component code Easier to perform an action on a value change.
Automatically tracks forms and input element state Reactive Trasformations→Debounce tiem or
distinct changed
Easily add input elements dynamically
Easier unit testing.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'tfdemo';
name:string;
SaveData(data){
console.log(data);
}
}
app.component.html
<form #myformref="ngForm" (ngSubmit)="SaveData(myformref)">
<div ngModelGroup="studentdetails">
<div class="row">
<label for="name">Name:</label>
<input type="text" name="Name" [(ngModel)]="name">
</div>
<div class="row">
<label for="email">Email:</label>
<input type="text" name="Email" ngModel>
</div>
</div>
<div ngModelGroup="coursedetails">
<div class="row">
<label for="Coursename">Coursename:</label>
<input type="text" name="Coursename" ngModel>
</div>
<div class="row">
<label for="Duration">Duration:</label>
<input type="text" name="Duration" ngModel>
</div>
<div class="row">
<label for="Fees">Fees:</label>
<input type="text" name="Fees" ngModel>
</div>
</div>
<br>
<button type="submit">Display</button>
</form>
<router-outlet></router-outlet>
Output:
Press fn+f12 to view all this.
Course name
Student details
Another way of storing same data as a single group:
<form #myformref="ngForm" (ngSubmit)="SaveData(myformref)">
<div class="row">
<label for="name">Name:</label>
<input type="text" name="Name" [(ngModel)]="name">
</div>
<div class="row">
<label for="email">Email:</label>
<input type="text" name="Email" ngModel>
</div>
<div class="row">
<label for="Coursename">Coursename:</label>
<input type="text" name="Coursename" ngModel>
</div>
<div class="row">
<label for="Duration">Duration:</label>
<input type="text" name="Duration" ngModel>
</div>
<div class="row">
<label for="Fees">Fees:</label>
<input type="text" name="Fees" ngModel>
</div>
<br>
<button type="submit">Display</button>
</form>
<router-outlet></router-outlet>
Output:
Reactive Forms
Create a project to display a reactive form which display the name,age,email and store all its values
in object?
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { from } from 'rxjs';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'rfdemo';
myform=new FormGroup(
{
name:new FormControl(),
age:new FormControl(),
email:new FormControl(),
}
);
SaveData(){
console.log(this.myform.value);
}
}
app.component.html
<form [formGroup]="myform" (ngSubmit)="SaveData()">
<div class="row">
<label for="name">name</label>
<input type="text"name="name" id="name" formControlName="name">
</div>
<div class="row">
<label for="age">age</label>
<input type="text"name="age" id="age" formControlName="age">
</div>
<div class="row">
<label for="email">email</label>
<input type="text"name="email" id="email" formControlName="email">
</div>
<button type="submit">Display</button>
</form>
<router-outlet></router-outlet>
Output:
Validations
Create a project to display a reactive form which display the name,age,email and store all its values
in object and validate the data?
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { from } from 'rxjs';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'rfdemo';
myform=new FormGroup(
{
name:new FormControl("",[Validators.required]),
age:new FormControl("",[Validators.required]),
email:new FormControl("",[Validators.required,Validators.email]),
}
);
SaveData(){
console.log(this.myform.value);
}
}
app.component.html
<form [formGroup]="myform" (ngSubmit)="SaveData()">
<div class="row">
<label for="name">name</label>
<input type="text"name="name" id="name" formControlName="name">
<span *ngIf="myform.controls.name.invalid && myform.controls.name.touched">Please ente
r name</span>
</div>
<div class="row">
<label for="age">age</label>
<input type="text"name="age" id="age" formControlName="age">
</div>
<div class="row">
<label for="email">email</label>
<input type="text"name="email" id="email" formControlName="email">
<span *ngIf="myform.controls.email.invalid && myform.controls.email.touched && myform.
controls.email.errors.required">Please enter email</span>
<span *ngIf="myform.controls.email.invalid && myform.controls.email.touched && myform.
controls.email.errors.email">Invalid emailId</span>
</div>
<button type="submit">Display</button>
</form>
<router-outlet></router-outlet>
Output:
Custom Validations
Command to create a class:ng g cl Agerange
Create a project to add custom validations to age of previous project?
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule,ReactiveFormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { from } from 'rxjs';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<form [formGroup]="myform" (ngSubmit)="SaveData()">
<div class="row">
<label for="name">name</label>
<input type="text"name="name" id="name" formControlName="name">
<span *ngIf="myform.controls.name.invalid && myform.controls.name.touched">Please ente
r name</span>
</div>
<div class="row">
<label for="age">age</label>
<input type="text"name="age" id="age" formControlName="age">
<span *ngIf="myform.get('age').invalid && myform.get('age').touched">Please enter age
between 18-25</span>
</div>
<div class="row">
<label for="email">email</label>
<input type="text"name="email" id="email" formControlName="email">
<span *ngIf="myform.controls.email.invalid && myform.controls.email.touched && myform.
controls.email.errors.required">Please enter email</span>
<span *ngIf="myform.controls.email.invalid && myform.controls.email.touched && myform.
controls.email.errors.email">Invalid emailId</span>
</div>
<button type="submit">Display</button>
</form>
<router-outlet></router-outlet>
app.component.ts
import { Component } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
import {Agerange} from './agerange';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'rfdemo';
myform=new FormGroup(
{
name:new FormControl("",[Validators.required]),
age:new FormControl("",[Agerange]),
email:new FormControl("",[Validators.required,Validators.email]),
}
);
SaveData(){
console.log(this.myform.value);
}
}
agerange.ts
import { AbstractControl } from '@angular/forms';
export function Agerange(control:AbstractControl) {
if (control.value>=18 && control.value<=25) {
return null;
}
else{
return {range:true}
}
}
Output:
Method example:
function f1()
{
console.log("i am function");
}
f1();
function f2(x:number,y:number)
{
console.log(x+y);
}
f2(6,3);
class Employee
function f3(e1:Employee) {
{ eno:number;
console.log(e1.eno+e1.ename); ename:string;
} }
var em:Employee=new Employee();
em.eno=101; em.ename="anil";
f3(em);
Create a project to display registration form using reactive forms and bootstraps?
1. install bootstrap
npm install bootstrap --save
2. goto angular.json
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.css"
],
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {ReactiveFormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Angular 9 Reactive Form Validation</h3>
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-
invalid': submitted && f.firstName.errors }" />
<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-
invalid': submitted && f.lastName.errors }" />
<div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-
invalid': submitted && f.email.errors }" />
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" formControlName="password" class="form-
control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
<div *ngIf="submitted && f.password.errors" class="invalid-feedback">
<div *ngIf="f.password.errors.required">Password is required</div>
<div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
</div>
</div>
<router-outlet></router-outlet>
Output:
https://stackblitz.com/edit/angular-6-reactive-form-validation?file=app%2Fapp.component.ts
Singleton Objects
Design Pattern:- Design Pattern is a readymade solution for already existing problems
singleton design pattern is a design pattern that restricts the object creation outside the class
1. multiple users connect to database to perform different operations in that case for every user a seperate
object is created for db connectivity because of that the no of objects will increase so instead of creating
multiple objects create a single instance(object) and that object was consumned by all the users.
2. Angular supports component based architecture if we want to invoke the service method in multiple
components we need to create object for the service class
class Service
{
}
class C1 class C2 class C3
{ { {
Service s1=new Service s1=new Service s1=new Service();
Service(); Service();
} } }
in the above example mutliple objects are created for service class so in order to control object creation
internally angular services are implemented as singleton classes in angular single instance was created for
service class and that instance was accessable in multiple components
===============================
Singleton.ts
class College
{
static c1:College;
cname:string;
caddress:string;
private constructor()
{
this.cname="sathya";
this.caddress="hyd";
}
static GetCollege():College
{
if(College.c1==null)
{
College.c1=new College();
}
return College.c1;
}
}
var o1:College=College.GetCollege();
console.log(o1.cname+o1.caddress);
var o2:College=College.GetCollege();
console.log(o2.cname+o2.caddress);
var o3:College=College.GetCollege();
console.log(o3.cname+o3.caddress);
Output:
sathyahyd
sathyahyd
sathyahyd
===========================================
Rules:-
1. create a private constructor
2. create a reference variable as static
3. create a static method
4. static method must return single instance
Parent class-Child class Communication
Create a project to show the communication between child class to parent class?
create a component with name ‘child’ ng g c child
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'childtoparent';
childdata:string;
ParentMethod(data){
this.childdata=data;
}
}
app.component.html
<div>
<h1>Parent Component</h1>
<p>{{childdata}}</p>
<app-child (notify)="ParentMethod($event)"></app-child>
</div>
<router-outlet></router-outlet>
child.component.ts
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Output()
notify:EventEmitter<string>=new EventEmitter<string>();
PassData(){
this.notify.emit("iam from child");
}
constructor() { }
ngOnInit(): void {
}
}
child.component.html
<div>
<p>Child Component </p>
<button type="submit" (click)="PassData()">click</button>
</div>
app.component.css
div{
background: lightgrey;
padding: 30px;
}
child.component.css
div{
background: red;
padding: 30px;
}
Output:
Depenedency Injection
It can be achieved in 3 ways:
• code without DI
• DI as Design Pattern
• DI as a Framework
Code without DI
DI as a design Patern:
DI is a coding pattern in which a class receives its dependencies from external sources rather than creating
them itself.
DI As a Framework
Observables
A sequence of items that arrive asynchronously over time.
HTTP call: single item
Single item: HTTP response
Create a project to demonstrate the use of observables?
1. install json server
npm install -g json-server
2. start json server
json-server --watch db.json
code for db.json
{
"employees": [
{"id":1,"name":"anil","age":30},
{"id":2,"name":"sunil","age":25},
{"id":3,"name":"ajay","age":23},
{"id":4,"name":"vijay","age":24},
{"id":5,"name":"john","age":26}
]
}
create a user service: ng g s services/users
users.serveice.ts
import { Injectable } from '@angular/core';
import{HttpClient} from '@angular/common/http';
import { IEmployee } from '../employee';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UsersService {
private _url:string="http://localhost:3000/employees";
constructor(private http:HttpClient) { }
GetUsers():Observable<IEmployee[]>
{
debugger;
return this.http.get<IEmployee[]>(this._url);
}
}
employee.ts(create this file under app folder)
export interface IEmployee
{
id:number;
name:string;
age:number;
}
code for app.component.ts
import{Component, OnInit } from '@angular/core';
import{ UsersService } from './services/users.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'servicesdemo';
users:any[];
constructor(private us:UsersService) { }
ngOnInit()
{ debugger;
this.us.GetUsers().subscribe(
data=>this.users=data);
}}
app.component.html:-
<!--The content below is only a placeholder and can be replaced.-->
<div>
<table>
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
</tr>
</table>
</div>
<router-outlet></router-outlet>
code for app.module.ts:-
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import{UsersService} from './services/users.service';
import{HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule
],
providers: [UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'observablesexception1';
public errorMsg;
users:any[];
constructor(private us:UsersService){}
ngOnInit(){
debugger;
this.us.GetUsers().subscribe(
data=>this.users=data,
error=>this.errorMsg=error
);
}
}
app.component.html:-
<!--The content below is only a placeholder and can be replaced.-->
<div>
<table>
<tr>
<th>id</th>
<th>Name</th>
<th>Age</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
</tr>
</table>
</div>
<router-outlet></router-outlet>
code for app.module.ts:-
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import{UsersService} from './services/users.service';
import{HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule
],
providers: [UsersService],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:
Custom Directives
1. Structural Directives(ngIf,ngFor,ngSwitch)
2. Custom Directives:-creating the directives depending on the user requirement
Ex:
If our webpage contains multiple text boxes, if it wants to display the text in “red color” or “accept only 10
numbers” we have to give same code repetitedly. Such repetited code can be placed in custom directives.
Create a project to create custom directive?
create a directive
ng g d allowtendigit
Example 1:
allowtendigits.directive.ts
import { Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appAllowtendigits]'
})
export class AllowtendigitsDirective implements OnInit{
constructor(private eleref:ElementRef) { }
ngOnInit(){
debugger;
this.eleref.nativeElement.style.color="red";
}
}
app.component.html
<div>
<input appAllowtendigits type="text">
</div>
<router-outlet></router-outlet>
Output:
Example 2:
app.componet.html
<div>
<input appAllowtendigits type="text">
</div>
<router-outlet></router-outlet>
Output:
console
Example 3:
allowtendigits.directive.ts
import { Directive, ElementRef, OnInit, HostListener } from '@angular/core';
@Directive({
selector: '[appAllowtendigits]'
})
export class AllowtendigitsDirective implements OnInit{
constructor(private eleref:ElementRef) { }
ngOnInit(){
debugger;
this.eleref.nativeElement.style.color="red";
}
@HostListener('keypress')
keypress()
{
if(this.eleref.nativeElement.value.length+1>10)
{
return false;
}
else
{
return true;
}
}
}
app.componet.html
<div>
<input appAllowtendigits type="text">
</div>
<router-outlet></router-outlet>
Output:
ViewChild
Example 2:
Example 3:
app.component.html:-
<!--The content below is only a placeholder and can be replaced.-->
<div>
<button type="button" #btn>Click me</button>
</div>
<app-second></app-second>
Note:- Here AppComponent is parentComponent
<app-second> will work like child component
Output:
Example 4:
debugger;
}
ChangeName(){
this.mycomponent.name="Hello Vijitha";
}
}
Second.component.html:-
<p>{{name}}</p>
Second.component.ts:-
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.css']
})
export class SecondComponent implements OnInit {
constructor() { }
name:string="Hello Bhargav";
ngOnInit(): void { }
}
Output: Before After clicking on button
Example 5:
Output:
Web Services
Major Technologies used in developing projects.
If bill the above products. Bill will be the amount of last item.
Http can not maintain the record of old data, So sessions ,cookies were used
WEB API
Creating a web api
Create a web api and integrate with angular.
Right click on controller-> add item
Install bootstrap
Create a project with name webapiproject to display webapi data in our angular ?
1. create register component: ng g c register
2. create a service: ng g s register
code for app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RegisterComponent } from './register/register.component';
import {FormsModule} from '@angular/forms';
import {RegisterService} from './register.service';
import { from } from 'rxjs';
import{HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
RegisterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [RegisterService],
bootstrap: [AppComponent]
})
export class AppModule { }
code for app.component.html
<app-register></app-register>
<router-outlet></router-outlet>
Output:
Id Fname Lname salary Department
1 Anil kumar 23000 CSE
2 Sunil kumar 43000 ECE
TravelBiz project
Travel Biz
Project
(A Web Application Project Developed by using Angular9)
By
SATHYA TECHNOLOGIES
2nd Floor,Sri Sai Arcade,Beside Aditya Trade Center
Ameerpet, Hyderabad-500038
Ph: 040-65538958/65538968/65538978
www.sathyatechnologies.com
ABSTRACT
Name of the
1. TravelBiz
Project
• Agent can access the appn and can book the tickets
• DayWise Reports
5. Reports • Weekly Reports
• Monthly Reports
UITechnologies:-HTML,JavaScript,CSS
Technologies and Clientside Frameworks:-Angular9,Bootstrap
6. Languages to be
Serverside Frameworks:-WebAPI
used
Programming Languages:- C#.net,Typescript