0% found this document useful (0 votes)
29 views

Angular

Uploaded by

abhinavtonde1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Angular

Uploaded by

abhinavtonde1
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 40

Day1

----
Angular is web framework used to develop frontend/UI for webapplication

Prerequisite:-
HTML(what you see),
CSS(how you see)
Bootstrap(optional)
JQuery(optional)
Basic Programming

***what is a web-application?
web-appln is an application which is hosted on webserver
eg:-facebook,amazon,flipkart,irctc,redbus,makemytrip...

****Web Application Approaches


------------------------------
1)MPA-Multi Page Application
----------------------------
traditional approach
web application which consists of multiple pages
full page refreshment

limitation
slow
degrades user experience

solution
AJAX-Asynchronous Javascript and XML parsing
enables partial page refreshment
added complexity to the webpages
---------------------------------------------------------

2)SPA-Single Page Application


-------------------------------
It is a type of web application where all webpages are integrated in single
page(shell page)
partial page refreshment
faster loading time
enhanced user experience

-----------------------------------------------------
SPA means website having single page
SPA is a webapplication where all the webpages are integrated into a single page

home.html

Register AboutUs Members feedback


--------- ------- -------- ---------

hfdkjfdgfdktjfdthrejthretrehgtrehtgrehtgrehtgretretgrhtgrhtgrehthgrthr
hfdkjfdgfdktjfdthrejthretrehgtrehtgrehtgrehtgretretgrhtgrhtgrehthgrthr
hfdkjfdgfdktjfdthrejthretrehgtrehtgrehtgrehtgretretgrhtgrhtgrehthgrthr
hfdkjfdgfdktjfdthrejthretrehgtrehtgrehtgrehtgretretgrhtgrhtgrehthgrthr
hfdkjfdgfdktjfdthrejthretrehgtrehtgrehtgrehtgretretgrhtgrhtgrehthgrthr

__________________________________________________________
In Multi Page App
_______________________________________________________________
home.html
LOgin Register AboutUs ....

_________________________________________________________________
register.html
`````````````````````````````
`````````````````````````````
````````````````````````````
_________________________________________________________________
aboutus.html
`````````````````````````````
`````````````````````````````
````````````````````````````
______________________________________________________________
-AngularJS is first version of Angular
uses HTML+Javascript
-follows controller architecture

-Angular is a client-side framework used to develop SPA


using HTML+Typescript
[Typescript gets converted to Javascript]
-follows component architecture
-------------------------------------------------------------

Software requirments for Typescript


i)Visual Studio Code(VSCode) ->Source code Editor
download https://code.visualstudio.com

ii)Node.js ->runtime environment for Angular appln


provides with server framework
download https://nodejs.org

Eclipse,VisualStudio(.Net)--->VSCode
JDK,CLR/.net fw--->Node.js
-------------------------------------------------------------

npm-node package manager


is a node utility provided to install s/ws thro terminal

steps
1)install visual studio code[setup]
2)install node.js [setup]

3)install typescript using node terminal[internet should be on]


open node terminal
go in the user folder [C:\Users\admin]
npm install -g typescript

4)open VSCode--->open folder where u want to save codes

5)create a file greeting.ts---->type typescript code-->save it


open node terminal
tsc greeting.ts [here ts code will get compiled to js code]
node greeting.js

compile---->tsc *.ts
run---->node *.js
ctrl++ increase textfont
ctrl-- decrease textfont
___________________________________________________________

In case VSCode Terminal doesnt work


Run the Windows PowerShell as RunAsAdministrator
type Set-ExecutionPolicy Unrestricted
exit and run compiler again

then type Y

----------------------------------------------------------

softwares
1)VSCode(Editor)
download https://code.visualstudio.com

2)Node.js(Execution Environment)
download https://nodejs.org

3)install typescript
open node terminal
go in the user folder [C:\Users\admin]
npm install -g typescript

npm-node package manager


node utility to install s/w using terminal

compile
tsc hello.ts--------->ts converted to js

run
node hello.js

In case VSCode Terminal doesnt work


Run the Windows PowerShell as RunAsAdministrator
type Set-ExecutionPolicy Unrestricted
then type Y

exit and run compiler again

Typescript
----------
1)developed by Microsoft(Anders Hejlsberg-designer of C#)

2)free & open source

3)TS is a compiled language [it gets compiled to JS]


hello.ts---compile--->hello.js
tsc hello.ts [here ts code will get compiled to js code]
node hello.js
JS is a interpreted language

4)TS is strongly typed[we need to provide datatype for the variables]


let x:number=10
let nm:string="Rohan";
let status:boolean=true;

**JS is loosely typed/dynamically typed language


var x;
x=10; x="hello"; x=new Date();

5)parent language/superset of Javascript

6)supports all platforms

7)TS is Object-oriented[supports all pillars just like java/.net]


**JS is object-based

8)used for writing logic of Angular applications

_____________________________________________________________

**Declaring a variable
let variable:datatype=value
eg:-
let rollno:number=10;
let name:string="Anders";
let status:boolean=true;

let result:any; just like var result;


result=90 or result="pass" or result=90.98
result=new Date();

let marks:number[]=[90,89,77,88];
let s1:Student=new Student();

_______________________________________________________________

**Conditional Statements
if
if-else
nested if-else
else-if ladder

we can use logical operators &&,||


we can use relational operators <,>,>=,<=,==,!=

nested if-else
----------------
if(expr1)
{
if(expr2){....}
else{....}
}
else{
if(expr2){....}
else{....}
}
elseif ladder
-------------
if(expr1){
.....
}
else if(expr2){
......
}
else if(expr3){
......
}
....
else{
.....
}
______________________________________________________________
Basic Labs
~~~~~~~~~~
Lab1)calculate simple interest(var decl)

Lab2)Profit or loss based on cost price & selling price of product


(if-else)

Lab3)based on age & gender print ROI in a bank


NonSenior Citizen
ROI-->10%
Senior Citizen
(Male) ROI--->11%
(Female)ROI--->12%

_____________________________________________________________

**Array
-Array is a homogeneous collection(All the elemnts are of same type)
-Array elements are accessed via index starts from 0 to size-1

syntax:-
let x:number=10;

let x:number[]=[10,20,30];
x.push(40);
x.push(50);
console.log(x.length)--->5

x[0]--->10
x[1]--->20
x[2]--->30

let arrname:datatype[]=[values]
eg:
let numlist1:number[]=[10,20,30];
let fruits:string[]=["mango","apple","grapes"];
let emps:Employee[]=[e1,e2,e3];
_____________________________________________________________
Accessing the array elements using
-----------------------------------
**traditional for loop
for(initialization;condition;update){...}

**for-of loop
used to iterate over the values any collection like any array
in a forward direction

for(let tempvar of collection){...}


eg:
let numlist1:number[]=[45,67,23,85];
numlist1.push(89);
for(let n of numlist1){
console.log(n);
}
code activity:-
print an array holding electronic brandnames using for..of loop
_____________________________________________________________
Array lab-
1)create an array holding car brands & print it in a sorted manner using for-of
loop.
Also add more elements using push method (array & for-of)

2)print an array in a reverse order (traditional forloop)

3)print count of all even elemnts in an array(array,for..of,%)

_____________________________________________________________

***Functions in Typescript
A function is a block of code that performs some task

syntax:-
function <functionName>(....):return type{
//body
}

//function defination
function greet(nm:string):void{
console.log("Hello "+nm);
}

//function call
greet("Jack");
greet("Jill");

default parameters in the function


-----------------------------------
function myfunc(num1:number=10,num2:number=20){....}
myfunc(88,99);
myfunc();
myfunc(55);
myfunc(,55); //not work

optional parameters in the function


-----------------------------------
function myfunc(num1:number=10,num2:number=20,num3?:number){....}
myfunc(88,99);
myfunc(88,99,33);

passing array to a function


-----------------------------------
function myfunc(arr:number[]):number{...}

myfunc([10,20,30,40]);
or
let a:number[]=[10,20,30,40];
myfunc(a);
________________________________________________________________
code activity
write a function calculatebill receiving 2 parameters
array of price & delivery charge(optional)

calculatebill([120,65,250,15,25]);
calculatebill([120,65,250,15,25],100);

________________________________________________________________
code activity2
**hint-let numarr:number[]=[0,0,0,0,0];
code activity:-
write a function scorecalculator which receives
1)scores of 5 rounds(use default args set value to zero)--array
2)extra points(optional)
& returns the totalscore

scorecalculator([8,7,5,8,10]);
scorecalculator([8,7,5,8,10],2);
scorecalculator();
_____________________________________________________________

1)marksheet.ts (function)
write a function printMarksheet receiving 3 parameters rollno,name,marks-array

which needs to print marksheet details as follows


rollno=..
student name=..
marks=[.....]
total=..
percentage=..

**write 2 more functions calTotal(receive marks) &


calPercentage(receive total) & invoke them from printMarksheet
_______________________________________________________________

2)parameterpassing.ts
write a function printBookInfo receiving
bookcode,title,author,price,discount[optional]

printBookInfo();
printBookInfo(101,"..","..",890);
printBookInfo(102,"..","..",790,10);

______________________________________________________________

**importing Modules
import {..} from 'path of the ts file w/o extension'
eg:-
import { greet, hello } from "./myfunc";
import {printTotal} from "./function";

myfunc.ts
----------
export function greet(){
console.log("Welcome to Typescript");
}
export function hello(){
console.log("Hello from Typescript");
}
callfunc.ts
------------
import {greet,hello} from './myfunc';

//caller code
greet();
hello();
--------------------------------------------------------

code activity:-
math.ts ---->sqrt,cube
caller.ts ----> ? import

eg:-
import {Component} from '@angular/core'
import {sqrt,cube} from '../../temp1/temp2/math';
_____________________________________________________________

Lab3)
create 2 files
math.ts
----------
write 2 functions square(num),cube(num)
[pass default parameter]

caller.ts
----------
call all the above 2 functions
square();
cube(10);

_______________________________________________________

**for-in loop
used to iterate over the index any collection like any array
for(let tempvar in collection){...}
eg:
let numlist1:number[]=[10,20,30,40,50];
for(let n in numlist1){
console.log(n);
}
output:-0 1 2 3 4
______________________________________________________________

Object oriented approach is a programming approach which models real world entities
as an object

**Object-oriented Approach--->Grady Booch--->book(OOAD)--->


Object Model(Rules or Guidelines for OOPS)
i)Major Pillars
Abstraction
Encapsulation
Inheritance
Polymorphism
ii)Minor Pillars
Strong Typing
Concurrency
Persistence

object-based language
object oriented languages(C++,Java,.net)still use primitives
purely object oriented languages-(small talk) no primitives

**Typescript as an object oriented language


-------------------------------------------
Writing a Typescript class
Object creation
Array of objects
Inheritance
interface

A class is a blueprint/template to create like objects

-TS filename & classname name can be anything

-constructor is defined using constructor keyword not classname

-we can have only one ctor in typescript class[default/parameterized]

-using this is mandatory inside a TS class

-when we define a function inside a class,we dont use the keyword function
function globalfunc():void{....}
let x:number=10;

class MyClass{
x:number;
localfunc():void{....}

-If my filename is Hello.ts


export class A{...}
export class B{...}
export class C{..}
test.ts
--------
import {A,B,C} from './Hello'

Code Activity
-------------
Product---->code,name,price
ctor Discount()----10% discount
Display()
let p1:Product=new Product(1024,'LAptop',89000);
p1.Discount();
p1.Display();
_____________________________________________________________

Lab 1)Class Writing & Object Creation


create 2 files
Player.ts
----------
Write a class Player--playerId,playerName,country,numMatches
ctor,DisplayInfo

caller1.ts
---------
create an array holding 2 player objects & print them using for-of loop
_____________________________________________________________

Day 4
-------
Inheritance
--------------
Inheritance is the property by the virtue of which one object acquire features of
another object

Person-fullName,gender,email
class Employee extends Person{empid,salary}
class Player extends Person{playerId,country,numMatches}
class Customer extends Person{custId}

we acheive code reusability as well as code extensibility


------------------------------------------------------
class Manager extends Employee
Manager is sub class/derived class/child class
Employee is super class/base class/parent class
------------------------------------------------------

Generic Reference
-----------------
class Student extends Person{
rollNo:number;
name:string;
marks:number[];
}

let s1:Student=new Student(...);

let s2:Person=new Student(...);


here s2 is a generic reference(super class reference holding sub class object.)

------------------------------------------------------
let p1:Batsman=new Batsman(.........);
let p2:Bowler=new Bowler(.........);

let parr:Player[]=[p1,p2];
parr.push(new Batsman(....));
parr.push(new Bowler(....));
here parr is a generic reference
super class reference holding sub class object.
------------------------------------------------------

Code Activity
--------------
class Person{fullName,gender,email Display(){....}}
class Customer .....{
custId,country,contact
Display(){............}
}
let c1:Customer=new Customer(....);
c1.Display();
___________________________________________________________________
Lab1) Inheritance & array of objects,generic reference
Player.ts
----------
Write a class Player--playerId,playerName,country,numMatches
ctor,DisplayInfo

Batsman.ts
------------
Write a class Batsman extends Player-->numRuns
ctor,DisplayInfo

Bowler.ts
------------
Write a class Bowler extends Player-->numWickets
ctor,DisplayInfo

caller2.ts
---------
create an array of Player type---team holding 2 Batsman object & 2 Bowler objects
& display all players using for-of loop

eg: let team:Player[]=[.....];

code:-
let b1:Batsman=new Batsman(....);
let b2:Batsman=new Batsman(....);
let b3:Bowler=new Bowler(....);
let b4:Bowler=new Bowler(....);

let team:Player[]=[b1,b2,b3,b4];
team.push(new Batsman(....));
team.push(new Bowler(....));
________________________________________________________________

Polymorphism=poly(many) + morph(form)
ability of a method to take many forms;
same method name but diff method implementations

implemented using Method Overloading & Method Overriding


______________________________________________________________________
Lab2)//Polymorphism on related objects(belonging to the same hierarchy)
--->abstract class(cannot be instantiated) & abstract method(does not have any
implementation)

Problem Statement:-Calculate Area of various shapes


shape.ts
-------------
abstract class Shape{abstract calArea();}
Circle-->radius
Rectangle--->l,b
Square--->side

testshape.ts
-------------
let cir:Circle=new Circle(50);
let rect:Rectangle=new Rectangle(25,10);
let sqr:Square=new Square(30);
let sarr:Shape[]=[cir,rect,sqr];
or
let sarr:Shape[]=[new Circle(50),new Rectangle(25,10),new Square(30)];

for(let t:sarr){
t.calArea();
}

_________________________________________________________________

interface
---------
interface is a contract/collection of guideliness
contains only abstract methods

use:-
interface is used to extend polymorphism over unrelated objects
interface is used to implement multiple inheritance
______________________________________________________________
class A extends B{}
Here class A is a subclass
______________________________________________________________
interface I{...}
class A implements I{}
Here class A is a Provider class
______________________________________________________________
class A extends B implements I1,I2,I3{..}
______________________________________________________________
interface I1{M1():void;}
interface I2{M2():void;}
interface I3 extends I1,I2{M3():void;}

class A implements I3{


M1():void{}
M2():void{}
M3():void{}
}
______________________________________________________________

-we cannot create object of an interface,but we can create its generic reference
IPrintable r=new Student();
INoisable r=new Cat();
_____________________________________________________
Lab3)Polymorphism on unrelated objects
Print/Display Student,Product & Manager objects.

interfacedemo1.ts
------------------
interface IPrintable{
Display():void;
}
class Student implements IPrintable{rollno,name,marks[]}

class Product implements IPrintable{


productId,productName,price}

class Manager extends Employee implements IPrintable{


incentives
}
Employee super class--->empId,empName,basicSal

client_interface1.ts
-------------------
let arr:IPrintable[]=[];
arr.push(new Student(....));

_________________________________________________________

Lab4)Interface
ITune.ts
---------
create an interface ITune having a method Play()

Instruments.ts
--------------
write 3 classes Guitar,Piano & Violin implementing the interface ITune

CallerInstrument.ts
-------------------
create an array instruments:ITune[] holding Guitar,Piano & Violin objects & invoke
Play method

___________________________________________________________________
Day 5
-----
download my-dream-app.zip(Angular Project)
extract it

AngularJS is first version of Angular


uses HTML+Javascript

i)Angular is a client-side framework used to develop SPA


using HTML+Typescript
[Typescript gets converted to Javascript]

ii)Angular ships with a lot of built in libraries .


for using it simply import the libraries
import {Component} from '@angular/core'
import {ReactiveForm} from '@angular/forms'
import {add,sub} from './math'
import java.util.Scanner

iii)Angular is component based


ProductComponent-->html[view]+css[appearance]+ts[logic]
-------------------------------------------------------------

**Understanding component-based architecture of angular application


-------------------------------------------------------

-Angular is a clientside framework used to develop SPA using HTML & Typescript

-Angular is component-based ???

-An Angular application comprises of Modules[nonvisual] & components[visual


element]

-Component is the basic building block of an Angular UI


-you can see the component[it is a visual element]

-Component is made up of 4 files


*.component.html [content]--what you see
*.component.css[appearance]--how
*.component.ts[logic]
*.component.spec.ts[for testing purpose]-optional

-ts file holds the component class which is decorated using


@Component({}) decorator

-@Component({}) decorator provides the metadata about a component

{{ }} is interpolation used to fetch value from ts file into the html file

eg:- creating a HelloComponent


hello.component.html [Template]
---------------------
<h1>{{title}}</h1>
hello.component.css
---------------------
h1{color:blue;font-size:25px;}

hello.component.ts
---------------------
@Component({
selector:'hello-comp',
templateUrl:'./hello.component.html',
styleUrl:['./hello.component.css']
})
export class HelloComponent{
title:string="Hello from SEED!!";
}

-component is identified using the selector name we specify in ts file


-every component must be registered in the Root Module
declarations[]

index.html(shell page)
--------------
<hello-comp/>-----------selector of HelloComponent
<header-comp/>
<article-comp/>
<categories-comp/>
<comments-comp/>
<news-comp/>
<footer-comp/>

______________________________________________________________
Welcome to SEED Infotech-----TitleComponent

COurses offered at SEED ----CoursesComponent


1)Testing courses
2)Programming Languages
3)Basic COurses

CopyRight@SeedInfotech ...-----CopyRightComponent

title.component.html/css/ts
courses.component.html/css/ts
copyright.component.html/css/ts
___________________________________________________________________

-An Angular application comprises of Modules[nonvisual] & components[visual


element]

Angular Module
---------------
-In ANgular,Module is a group of related components,directives,pipes & services

-Every Angular appln has a root module[AppModule] defined in app.module.ts

-Root module acts as an entry point & helps to assemble & link all parts of an
angular appln
eg:-create a module AppModule
app.module.ts
-------------
@NgModule{(
declarations:[AppComponent,HelloComponent,ProductComponent,AboutUsComponent],

imports:[list of user-defined/library modules],


providers:[],
bootstrap:[AppComponent]
)}
export class AppModule{}

-we can also create our userdefined modules


School--->Classes---->Students---->CR/MOnitor
Angular App--->Modules---->Components---->Bootstrap component
_____________________________________________________________
1 shopping module
2 components ---Product & Customer component

7 files
shopping.module.ts

product.component.html
product.component.css
product.component.ts

customer.component.html
customer.component.css
customer.component.ts
_____________________________________________________________

s/w requirements
-----------------
1)VSCode-Editor for angular appln
2)NOde.js-execution enviroment/server framework for angular appln
3)Typescript-logic of angular appln
node terminal
npm install -g typescript

4)Angular CLI[Command Line interface]


npm install -g @angular/cli

automates the development tasks in ANgular


-create a new Angular project
-preview
-run unit tests
-build

-how to install angular cli


open node terminal
npm install -g @angular/cli
or
npm install --save --only=dev @angular/cli@latest

****Run an Angular application


open vscode-->open my-dream-app [Angular Web Project]
open node terminal--->go in my-dream-app folder--->ng serve
[start the embedded server
& deploy the angular application on the server
& host it on http://localhost:4200]

open browser & paste link http://localhost:4200

Details
-------
my-dream-app> ng serve
starts embedded server
deploy the angular application[hosted on url http://localhost:4200]
open index.html web page
In index.html... <app-root>....selector name of AppComponent

HW
Modify my-dream-app
set some bgcolor
heading color -->maroon
change font
-------------------------------------------------
Welcome to SEED Infotech
logo
COurses offered at SEED
3 links 1)Testing courses
2)Programming Languages
3)Basic COurses
-------------------------------------------------

Day 6
------
Anatomy of ANgular Project
---------------------------
e2e[end-to-end]----> testing purpose
node-modules----> libraries
src----->area of working
app------>hold source code[components,modules]
assets---->images

my-dream-app>ng serve
starts embedded server
deploy the angular application & hosted on url http://localhost:4200
open index.html web page
In index.html... <app-root>....selector name of AppComponent

index.html---->
selector of bootstrap component(AppComponent)<app-root>----->
selector of all user-defined components

index.html---><app-root>----><userdefined comp>

Angular Appln--->Root Module---->Bootstrap comp+other components


(my-dream-app) (AppModule) (AppComponent)
steps to create components[HelloComponent]
-------------------------------------------
1)create 3 files in a folder hello
hello.component.html
hello.component.css
hello.component.ts(write the component class)

2)register HelloComponent in AppModule declarations array

3)use selector of HelloComponent in app.component.html


(not index.html)

<hello-comp>---->app.component.html
index.html--->App component----->selectors of user-defined components

_______________________________________________________________
Lab)
1)create a HelloComponent which prints
Hello from <your name>!!

2)create a CustomerComponent holding information of 5 customers in a tabular manner


eg:customer details(CustomerInfo)---> custId,custName,country,city,contactNo

___________________________________________________________________

Day 7
-----
Inline Template[template] & Inline Style[styles]
------------------------------------------------
-If html code is very less than instead of creating an external .html file,we will
write the html code in the component.ts itself
[Inline HTML/Template]

-Here we use template instead of templateUrl

so use
templateUrl-external html file
template-inline html code

styleUrls-external css file


styles-inline css code
_______________________________________________________

Nested Components
-----------------
here we will create 2 components
parent-comp & child-comp

we will use selector of child-comp inside parent-comp


we will use parent selector in app.component.html

Eg:-
app.component.html
---------------------
<parent-comp></parent-comp>
parent.component.html
---------------------
This is parent component
<child-comp></child-comp>

steps:
1)create the child component
2)create the parent component.Use child-comp selector inside parent-comp
html/template

3)register both parent & child comp in root module


4)use parent-comp selector in the app.component.html

_______________________________________________________
Lab1)create a Greeting component using inline html & css
which prints
Welcome to the world of Angular!!!

Lab2)output of nested comp [do not use inline concept]


Parent Comp output
-------------------
Corona cases Summary
Total Cases = {{}}
Cured Patients={{}}
Death Cases={{}}

Child Comp output


-------------------
Table showing details
City Place Positive Cases Cured Patients Death Cases
[This data will come from array of objects-CaseInfo]

CaseInfo.ts
City,Place,Positive Cases,Cured Patients,Death Cases

7 files
Parent.component.html/css/ts
Child.component.html/css/ts
CaseInfo.ts

____________________________________________________________

Angular Directives
------------------
Directive is additional marker on the DOM/HTML element which adds new behavior to
that DOM element

<h1>Welcome to Shopping App</h1>

<h1 *ngIf="status">Welcome to Shopping App</h1>

<table *ngIf="found">
</table>

<li *ngFor="">item</li>
<product-comp></product-comp>

Angular Directives
------------------
1)Component(user-defined tag/tag with template)

2)Structural Directives:-
---------------------
-change the layout of the webpage by adding/removing DOM element
-structural directives are easily recognized using an asterisk(*) that precedes it
eg:-*ngIf,*ngFor,[ngSwitch]

3)Attribute Directives:-
____________________________________________________________

*ngIf directive
----------------
simplest directive which takes a boolean expression & makes the entire chunk of the
DOM appear or disappear

*ngIf is used to show/hide DOM element

eg:-
<h1 *ngIf="status">Welcome to the world of Angular Directives!!</h1>

<div *ngIf="show">
.....
</div>

<table *ngIf="found">
</table>
____________________________________________________________

*ngFor directive
------------------
used to iterate over collections like an array & create an element for each item

*ngFor is used to repeat a DOM element

syntax:-
*ngFor="let variable of variablelist/collection";
Here the variable is a temporary variable to display the values in variablelist
____________________________________________________________

Lab3)CarComponent
Display a heading & unordered list of car brands(fetched from an array of string)

List of the Best Car brands ----- use *ngIf="show"

. Maruti ------use *ngFor


. Mustang
. Volkswagen
. Hyundai
. Honda

Lab4)Modify CustomerComponent to use *ngFor


Reference of previous assignment
create a CustomerComponent holding information of 5 customers in a tabular manner
eg:customer details--->custId,custName,country,city,contactNo
____________________________________________________________

Day 8
------
In the previous session we learnt
Angular Directive
-----------------
1)Component--->tag with a template
<product-info></product-info>

2)Structural Directives--->change the layout of the webpage by adding/removing DOM


element
*ngIf,*ngFor,[ngSwitch]

switch(x){
case 1:hjhjhgjhgj
case 2:hjhjhjhgjhg
....
default:hjhgjhgj
}

[] property binding syntax


[ngSwitch] directive
--------------------
Ngswitch is an angular directive that displays one elemnt from a possible set of
elements based on dom condition.

It uses ngSwitchCase keyword to define set of possible elements and


ngSwitchDefault to define default value when condition does not match

_____________________________________________________________

Lab1) OrderComponent

Display Order Details in a tabular form with following colors


orderStatus bgcolor forecolor
cancelled--->red white
pending---->orange white
processed --->green white

OUTPUT
Order Summary

orderNo orderDate customerName contactNo city orderStatus [*ngFor & ngSwitch]

hint:-
oarr:any[]=[
{"orderNo":1023,"orderDate":"20-feb-22","customerName":"George",
"contactNo":"898655444","city":"NY","orderStatus":"pending"}
];
_____________________________________________________________

Pipes
-----
Using pipes help Angular to display data in the desired format

str:string="hello";
{{str}} --->hello
{{str|upperCase}} --->HELLO
{{str|titleCase}} --->Hello

salary:number=1000;
{{salary}} ---------->1000
{{salary|currency:"USD"}}-------->$1000
{{salary|currency:"EUR"}}-------->E1000

syntax:-
{{expression|pipe1:arg|pipe2:arg}}
eg:-
{{lastName|titlecase}}
{{birthdate|date:"mediumDate"}}
{{salary|currency:"USD"}}

json--->java script object notation

Built-in Pipes
---------------
date :- converts expression to a date format
currency:- formats a number as currency
uppercase/lowercase/titlecase:- text transformation
json:- used to pretty print object
number:- format a number[decimal places,rounding]

new Date(year,month,day); //month starts from zero


Examples:-

<h4>Currency Pipe Example</h4>


<p>Amount is {{amount}}</p>
<p>Amount is {{amount | currency:'USD':true}}</p>
<p>Amount is {{amount | currency:'EUR':true}}</p>
<p>Amount is {{amount | currency:'INR':true}}</p>

<hr>
<h4>Number Pipe Example</h4>
<p>Number is {{75|number:'2.3-5'}}</p>
<p>Number is {{75|number:'3.2-5'}}</p>
<hr>
<h4>Date Pipe Example</h4>
<p>Joining Date is {{jdate|date:"mediumDate"}}</p>
<p>Joining Date is {{jdate|date:"dd/MM/yyyy"}}</p>
<p>Joining Date is {{jdate|date:"fullDate"}}</p>
<p>Joining Date is {{jdate|date:"shortTime"}}</p>
<hr>
<h4>Uppercase pipe</h4>
<p>{{"seed"|uppercase}}</p>
<hr>
<h4>Lowercase pipe</h4>
<p>{{"SEED"|lowercase}}</p>
<hr>
<h4>Titlecase pipe</h4>
<p>{{"seed"|titlecase}}</p>
<hr>
<p>{{person.firstName}} {{person.lastName}} {{person.gender}}</p>
<h4>JSON pipe</h4>
<pre>{{person|json}}</pre>
_____________________________________________________________

Lab2)create a folder pipedemo holding EmployeeComponent


which print 10 employees inf in a tabular manner as follows

Employee--->
empId [number]
firstName [titlecase]
lastName [uppercase]
birthDate [date]
annualSalary [currency]
country [India,United Kingdom,United States of
America,Australia]

eg:-
<tr *ngFor="let e of earr">
<td>{{e.fname|titlecase}}</td>
</tr>
______________________________________________________________
Angular=Module+Component+Directive+Pipe

applying multiple pipes


----------------------
{{country|code|uppercase}}
India------>ind-------->IND
United Kingdom------>uk-------->UK
Australia--------->aus--------->AUS

{{75|number|currency}}

student component----->3 files student.component.ts/html/css]


@Component({selector,templateUrl,stylesurl,template,styles})

college module----->1 file[college.module.ts]


@NgModule({declarations,imports,providers,bootstrap})

reverse pipe----->1 file [reverse.pipe.ts]


@Pipe({name})

Custom/user-defined Pipe
--------------------------
steps:
1)Create a typescript class named as ReversePipe[reverse.pipe.ts]
2)import Pipe & PipeTransform interface from angular core module
3)Decorate class with @Pipe [where we define custom pipe name]
4)implement PipeTransform interface & override transform() method
5)register custom pipe in the app.module.ts

reverse.pipe.ts
---------------
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({
name:'reversepipe'
})
export class ReversePipe implements PipeTransform{

transform(value:string):string{
let newStr:string="";
for(var i=value.length-1;i>=0;i--){
newStr+=value.charAt(i);
}
return

}
}
app.component.html
------------------
<p>{{"Welcome to the world of Angular"|reversepipe}}</p>
<p>{{"Hello Batch"|reversepipe}}</p>
____________________________________________________________

Lab2 continued)In the previous lab ie EmployeeComponent


create a custom pipe named as countrycode
countryname---->convert to its code
{{empObj.country|countrycode}}
eg:-India--->IND
Australia------>AUS
United Kingdom------->UK
United States of America---->USA

hint:-
transform(value:string):string{
if(value=='India')
return 'IND';
else if(value=='Australia')
return 'AUS';
............
}
_____________________________________________________________
Day 9
------
Directives
----------
1)Component

2)Structural Directives--->change layout of the webpage


*ngIf,*ngFor,[ngSwitch]

<h1 *ngIf="show">hello</h1>
<h1 *ngFor="let t of arr">hello {{t}}</h1>

3)Attribute Directives:- change the appearance of DOM elements


---------------------
ngStyle directive
-----------------
It binds the style with the component variables[ts file]
eg:-
//Traditional approach
<p style="color:red">Hello</p>
Here the value red is static/fixed

<p style="color:red;font-family:fantasy;font-size:25px">Hello</p>
//Angular approach
<p [ngStyle]="{'color':clr}">Hello</p>
Here clr is a component variable
Here [] indicate property binding syntax
Here clr being a variable its value is dynamic

[ngStyle]="{'key':value}"
[ngStyle]="{'key1':value1,'key2':value2}"

eg:-<p [ngStyle]="{'color':clr,'font-size':fsize+'px'}">This is a paragraph</p>

.ts file(component class)


clr:string="blue"
fsize:number=25

code activity:-
--------------
show <h1>Hello</h1>
clr,bc,fsize(component variables)
clr:string="red";
bc:string="yellow";
fsize:number=30;

solution
<h1 [ngStyle]="{'color':clr,
'background-color':bc,'font-size':fsize+'px'}">Hello</h1>
____________________________________________________________
ngClass directive
-----------------
It binds the style with the css class[css file]

//Traditional approach

<div class="mystyle">.......</div>

//Angular approach
Array Syntax
<div [ngClass]="['mystyle1','mystyle2']">.......</div>
String Syntax
<div [ngClass]="'mystyle1 mystyle2'">.......</div>
Object Syntax
<div [ngClass]="'mystyle1':true,'mystyle2':true">.......</div>
__________________________________________________________
Lab1)create a AttrComponent
show a heading----- About Myself [use ngStyle]
[color,font-family,font-size,background-color]

In the above component


create a 3 divs holding your information.
Apply css class using [ngClass]

.css file
----------
.floral{}
.ocean{}
.sunset{}
OUTPUT:-
<h1>About Myself<h1>----------------------------------use ngStyle
<div>gjhfjkghdfjghdfjgfdghdfjgh</div>---use ngClass Array syntax
<div>gjhfjkghdfjghdfjgfdghdfjgh</div>---use ngClass String syntax
<div>gjhfjkghdfjghdfjgfdghdfjgh</div>---use ngClass Object syntax
__________________________________________________________

Batch Module---- batch.module.ts

@NgModule({...})
export class BatchModule{}

Course Component----
course.component.html
course.component.css
course.component.ts

@Component({...})
export class CourseComponent{}

ReversePipe------------ reverse.pipe.ts
@Pipe({name})
export class ReversePipe{..}

HighLightDirective -------- highlight.directive.ts


@Directive({...})
export class HighLightDirective{}

<h1 *ngIf="status">Hello</h1> Predefined Directive

<h1 highlight>Hello</h1> user-defined/custom directive


<p highlight>Hi</p>

Custom Directive
-----------------
steps:-
1) Create a class decorated with @Directive({}) in the file
<directive_name>.directive.ts

2) Provide selector enclosed in bracket []

3) Use ElementRef class to access DOM to change the host element appearance.

4) REgister the custom attr directive in the application module within the
declaration block.[same way as we declare component]

5)use the selector in app.component.html

Lab2)
Create a custom directive CapsDirective which changes the content to uppercase
<h1 capsdir>This is a heading</h1>
<p capsdir>This is a paragraph</p>
<div><table><ul><ol><fieldset>
hint:-
e1.nativeElement.style.textTransform="uppercase"
____________________________________________________________
Day 10
-------
Angular Data Binding
---------------
Auto synchronization of data between Source[component class .ts file] & View[.html]
is called as binding

S --------> V {{}} []
S <-------- V ()
S <--------> V [()]

Binding types
1)one way binding from source to view
S --------> V
interpolation {{}}
property binding []

2)one way binding from view to source S <-------- V


Here we perform some action in the view & some function in the source/component
class gets invoked.
event binding ()

3)two way from S to V & V to S S <--------> V


Banana in the box syntax [()]

___________________________________________________________
**to use 2-way binding syntax
import FormsModule from '@angular/forms'
app.module.ts
-------------
import { FormsModule } from '@angular/forms';
imports: [BrowserModule,FormsModule]
___________________________________________________________
Examples:-
mycomp.component.ts [source]
---------------------
@Component({})
class MyComp{
msg:string="hello";
}

mycomp.component.html [view]
---------------------
{{msg}}

___________________________________________________________
**paste the images in the src-->assets-->images folder
path="assets/images/*.jpg"

___________________________________________________________
Lab1) use []
create onewaybindingcomponent
show an image whose src,width & height can be customized thro component class

Lab2)use () {{}} [()]


create a calculatorcomponent
[hint : use <input type="number"/>]
first No textbox1
Second No textbox2
Add Sub Multiply Divide (buttons)
output

Lab3) citycomponent
drop down holding city names ----[()]
button click-----------------()
img of that city---------------[]
ordered list of the tourist places---------*ngFor show output

___________________________________________________________

Day 11
--------
Routing [ Navigation based on the request URL]
-------
Routing is the process of changing the state the application by loading diff
components based on request URL

steps:-
1)create the components

2)configure routes in app.routing.ts [Routing Configuration file] [keep it in


src/app folder]
Here we declare a routing variable which defines array of routes that map a path to
a component.
Each route maps path to a component

3)Register the following in app.module.ts


components in declarations[]
import RouterModule from '@angular/router'
routing variable

4)configure links in the app.component.html[Shell page]


routerLink directive used with anchor tags provide the navigation paths
router-outlet directive acts as a placeholder where matched components are
inserted/injected

<nav>
<a routerLink="path1">Home</a>
<a routerLink="path2">Message</a>
<a routerLink="path3">Photos</a>
</nav>
<router-outlet></router-outlet>

short steps
1)create components
2)configure routes [app.routing.ts]
3)register components & import libraries[app.module.ts]
4)configure links[app.component.html]
__________________________________________________________________
To create a new Angular Project
d:>ng new my-prj
d:>cd my-prj

**To run the Angular Project


d:>my-prj>ngserve

**To create a component


d:>my-prj>ng g c hello
It creates a hello folder containing 3 component files & registers the
HelloComponent in app.module.ts
______________________________________________________________

Lab) Royal Rider Club Application

Royal Rider Club Application


Home---->HomeComponent
Members---->MembersComponent
Events---->EventsComponent
output:-

Welcome to Royal Rider Club


*******************************
Home | Members | Events

<router-outlet>

*******************************
developed by ..............

______________________________________________________________
src--->app-->
royal_riders (folder)
home (subfolder)
home.component.html/css/ts
member
member.component.html/css/ts
event
event.component.html/css/ts
notfound
notfound.component.html/css/ts
______________________________________________________________
HomeComponent output
---------------------
About Royal Riders Club (heading)
Image
Description about the club(paragraph)

hint:-
home.component.ts--->3 variables--->about,imgpath,desc
home.component.html--->{{about}},[src]=imgpath,{{desc}}
______________________________________________________________
MembersComponent output
---------------------

Members @Royal Riders

Table holding member information [fetched from array of Member objects]

hint:-
members.component.ts--->array of Member objects
members.component.html--->access array using *ngFor(also use pipes)
Member.ts---> firstName,lastName,email,birthdate,contact,city,photopath

______________________________________________________________

EventsComponent output
---------------------
Events @Royal Riders

Table holding events information [fetched from array of Event objects]

hint:-
events.component.ts--->array of Event objects
events.component.html--->access array using *ngFor
Event.ts--->EventName,EventDate,From,To,Address,ContactNo(pipes)
______________________________________________________________

Day 12
--------
Angular Forms are build on the top of HTML form
--------------
HTML form is used to take input
<form>
<label>
<input type="text/password/radio/checkbox/button/submit/reset/email/color/
number/date/file"/>
<textarea>
<select>
</form>

.ts file ---> let r:number=10;


.html file ----> #r=10;
we define any template variable using # symbol

#userForm="ngForm"
means that userForm is a template variable
holding data from the form

<pre>{{empObj|json}}</pre>

Angular forms
-------------
1)Template Driven Form
-----------------------
Here form data is exported to a JSON object,which is then passed to the component
class & consumed.

we use
NgForm directive is used with HTML form tag to pass entire form data to a JSON
object

NgModel directive is used in form fields to bind the form data with the JSON object

steps
1)import FormsModule from '@angular/forms'
in app.module.ts

2) use ngForm & ngModel within the html form


<form #myform="ngForm">
<input type="text" name="pname" ngModel>
<input type="text" name="age" ngModel>
<input type="text" name="hobby" ngModel>
<button type="submit">
</form>

{{myform.value|json}}
_________________________________________________________
Lab)create a registercomponent
Registration form
--------------------
firstname
middlename[dont bind]
lastname
gender[radio]
birthdate[date picker]input type="date"
city[dropdown]
contactNo
address[textarea]
submit & clear button

Summary (tabular manner)

PersonName ... ...


Gender ...
Birthdate ...
City ...
ContactNO ...

**********use pipes like uppercase,date,titlecase


**on click of clear button invoke a function ClearForm()--->reset JSON

Add a link register in the Royal Rider Application


when you click the register link,inject registercomponent in the <router-outlet>
Welcome to Royal Rider Club
*******************************
Home | Members | Events | Register

<router-outlet>

*******************************
developed by ..............
_________________________________________________________

Component Communication
-----------------------
In Angular a component can share data & information with another component by
passing data
Passing data from parent component to the child component can be done using @Input
decorator.

1)Declare a receiving property in child using @Input decorator


so that its value can be set from parent
eg:- @Input() childmsg:string;

2)Bind parent & child variable using []


To pass a value to the child component ,we need to pass it in square bracket []
eg:-<child-comp [childmsg]="sendmsg"></child-comp>

___________________________________________________________
code activity
-------------
parent-comp----->x
child-comp------->@Input() y

<child-comp [y]="x"></child-comp>
___________________________________________________________

Lab) create folder compcommunication


create 2 components MessageParentComponent[msg1] p-comp
MessageChildComponent[msg2] c-comp
pass the data from msg1 to msg2 using @Input() decorator
___________________________________________________________

challenge lab
-------------
create a mobilecomponent (to understand binding)
dropdown holding mobile modelnames
button-show details

Mobile Model Name(h1)


photo (img)
Description(p)
Features (ul)
Price(h2)

hint:-
minfo:any[]=[
{'model';'Samsung Galaxy','photopath':'assets/images/samsung.jpg',
'desc':'...','features':['','',''],price:89000.00}
];
____________________________________________________________

Day 13
------
2)Model Driven Forms (also called as Reactive forms)
-------------------
Here the form Model (form elements,values,validations) is defined in the component
class which is exported to a JSON which is then bound with the actual form in html.

steps
1)import ReactiveFormsModule from '@angular/forms'
in app.module.ts

2)define form model in the component class


userForm=new FormGroup({
fname:new FormControl('Rohit',Validators.required),
age:new FormControl(10,[Validators.required,Validators.max
(100),Validators.min(1)]),
city:new FormControl('Pune',Validators.required),
});

3) use [formGroup] & formControlName within the html form


<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
<input type="text" formControlName="fname">
<input type="text" formControlName="age">
<button type="submit">
</form>

yesterday(TemplateDriven forms)
<form #userForm="ngForm" (ngSubmit)="onFormSubmit(userForm)">
<input type="text" ngModel name="pname">
<input type="text" ngModel name="age">
<button type="submit">
</form>

steps for validation


--------------------
*.component.ts
--------------
get age:any(){
return this.userForm.get('age');
}
____________________________________________________________
*.component.html
--------------
<label>Age</label>
<input type="text" formControlName="age">
<span *ngIf="age.invalid" [ngClass]="'error'">Please provide proper Age</span>
<br>
____________________________________________________________
*.component.css
--------------
.error{
color:red;
background-color: yellow;
}
__________________________________________________________

Lab)In the Royal Rider App


Add a link Feedback in the Royal Rider Application
when you click the Feedback link,inject feedbackcomponent in the <router-outlet>
_________________________________________________________
Welcome to Royal Rider Club
*******************************
Home | Members | Events | Register | Feedback

<router-outlet>

*******************************
developed by ..............
_________________________________________________________
create a feedbackcomponent which displays a
Feedback Form (using ModelDrivenForm)
-------------
Person Name (text)
Feedback Date (text)
Rating [1-5] (number)
Comments (textarea)
submit button

Summary of the Feedback (tabular manner)


------------------------
Person Name ..
Feedback Date ..
Rating ..
Comments ..
_______________________________________________________

**apply following validations


All fields are mandatory
min rating is 1 & max is 5
__________________________________________________________

**challenge lab form-based


Employee Form
Employee Id textbox
Employee Name textbox
Salary textbox
Submit Reset

Table showing All the Employees added thro the form

use
Array of objects,push,json,angular form,binding,(ngSubmit)
*ngFor,*ngIf,ngClass
__________________________________________________________

Reference
The Angular safe navigation operator (?.) is a fluent and convenient way to guard
against null and undefined values in property paths. Here it is, protecting against
a view render failure if the currentHero is null.

This specifically means that if the value you are binding to the view is null then
it should return null else the actual value, so that you dont get any issues while
rendering the template.
In the above sample code you provided ,

product?.id
it checks whether product object exists or not
______________________________________________________________

Day 14
-------
An Angular application comprises of
1)Module -integration/link diff parts of Angular appln
2)Component -UI
3)Directive -additional syntax with DOM
4)Pipe - Format output
5)Service-Business Logic

mycomp.component.html(template)
<button (click)="m1()">Click Here</button>

mycomp.component.ts(component class)
m1(){invoke data service}

data.service.ts(Angular service)
fetch the data logic
searchservice

Services in Angular
------------------
An Angular service is a class that encapsulates some sort of desired business
functionality

How to create a Angular service


-------------------------------
1)create a file named as servicename.service.ts
2)create a class decorated with @Injectable decorator
3)write business methods in the class

**register the service we have 2 ways


In app.module.ts or component class
providers:[HelloService]

How to consume the service


---------------------------
1) Create a component that consumes service

2) Register the service in the component metadata providers[]

3) Add a constructor that defines a private property of the type service

4)invoke the methods of the service using the reference passed to the ctor
_____________________________________________________________
Lab1)
create a MathService having 4 methods add,sub,multiply,divide
create a TestMathComponent to consume the service

output:-
First Number (input type number)
Second Number (input type number)
Add Subtract Multiply Divide (buttons)
{{output}}
On click of button Add--->doAdd() fn of Component--->add() fn service
_________________________________________________________________

Lab2)Challenge Assignment-optional
create a SearchService having a method search receiving name of the political party
name & it returns its information

create a TestSearchComponent to consume the service


output:-

textbox/dropdown holding political parties names


button ---->click invoke the searchservice method
logo
ChairPerson
information
_________________________________________________________
Day 15
------
Angular app(front end)<--url-->
REST API/WebService(Java-SpringBoot/.Net/Python)<---->
oracle/sql server db
Angular app(front end)<--url-->
Dummy Database(Angular InMemory-Web-API)
HttpClient service (Pre-defined Angular Service)
------------------
Angular HTTP Library provides us with a predefined module named as HttpClientModule

has a service HttpClient used for server communication over http


It has a get() method is used to fetch data from server.
It accepts a url & connects to it ,fetches data & returns it

HttpClientModule---->HttpClient service----->get(url)---->returns an
Observables--->subscribe

methods
get/post/put/delete

this.http.get(url).subscribe(success callback,error callback)

get(url).subscribe(
data=>{success handler},
error=>{err handler}
);

________________________________________________________________
**setup:-copy 2 folders in my-dream-app
angular-in-memory-web-api [backend]
rxjs-compat [Observable]
or

npm install -g angular-in-memory-web-api


npm install -g rxjs
________________________________________________________________
angular-in-memory-web-api (simulates REST API) creates a dummy db
RxJs-Reactive Extension for Javascript

forRoot is a static method in the InMemoryWebApiModule module


which configures the datasource

**steps to fetch the data using HttpClient service:-


1)import HttpClientModule in app.module.ts
2)inject the HttpClient service into the component using constructor
3)using service ref invoke get(url) method
syntax:-
http.get(url).subscribe(success code,error code)
http.get(url).subscribe(data=>{code},error=>{code})

-----------------------------------------------------
**How to create the backend (dummy database or you can use
REST API[.net,python,springboot])
1)create an in-memory DB by writing a class implementing InMemoryDbService
export class BookData implements InMemoryDbService {
createDb() {
}

2)import InMemoryWebApiModule.forRoot(BookData) in app.module.ts


_________________________________________________________

First run class demo on your PC & edit it to show workshop data

Lab)create a component DataComponent which fetches tourism information using


HttpClient service

output:-
button fetch data
table/error message

City Information State Tourist Places(array)

hint:-
{"city":"Pune","info":"Pune...","state":"MH",
"touristplaces":["..","..","..",".."]}

data.component.ts/html/css
city.ts
db.ts
_________________________________________________________

dAY 16
-------
Angular Application
One Root Module(AppModule)
multiple submodules
Each submodule will have multiple components
All submodules need to be imported in the root module

Seed Infotech Application


BatchModule--->c1,c2,c3
StudentModule--->c4,c5
FacultyModule--->c6,c7
CourseMOdule---->c8,c9,c10
whenever any module is imported in the root module,its components are directly
available in the root module

Creating User-defined Module in Angular


---------------------------------------
Lets create a module named SubModule having 2 components FirstComponent &
SecondComponent

we need to create 7 files as follows


first.component.ts
first.component.html
first.component.css

second.component.ts
second.component.html
second.component.css

submodule.module.ts

steps:-
1)create a file named submodule.module.ts

2)create a class SubModule annoted with @NgModule decorator

3)define the components & register in


declarations:[FirstComponent,SecondComponent]
exports:[FirstComponent,SecondComponent]

4)import this module in the root module[app.module.ts]


imports: [SubModule]
As soon as a module is imported in the root module,its components are also
automatically available to the Angular Application

Lab1)
create 2 user-defined modules
SubModule1--->FirstComponent,SecondComponent
SubModule2--->ThirdComponent,FourthComponent

import both submodules in RootModule & use its components


app.component.html
<first-comp></first-comp>
<second-comp></second-comp>
<third-comp></third-comp>
<fourth-comp></fourth-comp>
_____________________________________________________________

@Output decorator
-----------------
used to pass/emit custom event from child to parent

P -----> C @Input decorator we pass data from P to C


C -----> P @Output decorator we emit custom event from
C to P

event is raised in child but method of parent is called


data is passed from child to parent
flow
----
child action--->event object created & emit(data)--->parent method invoke

code activity
-----------------
parent-comp--->check(str)
child-comp--->myevent

@Output() myevent=new EventEmitter<string>();


<child-comp (myevent)=check($event)></child-comp>

eg:-
@Output() eventObj=new EventEmitter<string>();
<dictchild-comp (eventObj)="onwordchange($event)">
</dictchild-comp>
______________________________________________________________

Lab2)
pass cityname from child &
print following details in parent

City Name {{}}


Photo <img>
description {{}}
tourist places <ul><li>

hint:-
if(this.arr[i].cityname==city){
imagepath="assets/images/"+city+".jpg";
}
____________________________________________________________

Angular CLI commands


--------------------
1)To create a new Angular Project
ng new <projectName>

2)To create a component


go in the project folder
ng g component <ComponentName>
ng g c <ComponentName>

It will create 4 files[html/css/ts/spec.ts] in a folder

d:\ng new my-prj


d:\myprj\ng g c hello

___________________________________________________________________

In case VSCode Terminal doesnt work


Run the Windows PowerShell as RunAsAdministrator
type Set-ExecutionPolicy Unrestricted
exit and run compiler again

then type Y

ForRoot is used when a module is “eager,” that is, it is not lazy-loaded (loads
when the application starts). Angular creates a factory for all the modules, except
for the lazy modules, which when loaded on demand, have their own factory. When we
use forRoot(), we’re loading a provider that is going to be injected into the
“root” of the modules because it uses the same factory as our main module.

netstat -o -n -a | findstr 0.0:4200

You might also like