Angular
Angular
----
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...
limitation
slow
degrades user experience
solution
AJAX-Asynchronous Javascript and XML parsing
enables partial page refreshment
added complexity to the webpages
---------------------------------------------------------
-----------------------------------------------------
SPA means website having single page
SPA is a webapplication where all the webpages are integrated into a single page
home.html
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
Eclipse,VisualStudio(.Net)--->VSCode
JDK,CLR/.net fw--->Node.js
-------------------------------------------------------------
steps
1)install visual studio code[setup]
2)install node.js [setup]
compile---->tsc *.ts
run---->node *.js
ctrl++ increase textfont
ctrl-- decrease textfont
___________________________________________________________
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
compile
tsc hello.ts--------->ts converted to js
run
node hello.js
Typescript
----------
1)developed by Microsoft(Anders Hejlsberg-designer of C#)
_____________________________________________________________
**Declaring a variable
let variable:datatype=value
eg:-
let rollno:number=10;
let name:string="Anders";
let status:boolean=true;
let marks:number[]=[90,89,77,88];
let s1:Student=new Student();
_______________________________________________________________
**Conditional Statements
if
if-else
nested if-else
else-if ladder
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)
_____________________________________________________________
**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
_____________________________________________________________
***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");
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
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-based language
object oriented languages(C++,Java,.net)still use primitives
purely object oriented languages-(small talk) no primitives
-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{....}
Code Activity
-------------
Product---->code,name,price
ctor Discount()----10% discount
Display()
let p1:Product=new Product(1024,'LAptop',89000);
p1.Discount();
p1.Display();
_____________________________________________________________
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}
Generic Reference
-----------------
class Student extends Person{
rollNo:number;
name:string;
marks:number[];
}
------------------------------------------------------
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
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
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;}
-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[]}
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
-Angular is a clientside framework used to develop SPA using HTML & Typescript
{{ }} is interpolation used to fetch value from ts file into the html file
hello.component.ts
---------------------
@Component({
selector:'hello-comp',
templateUrl:'./hello.component.html',
styleUrl:['./hello.component.css']
})
export class HelloComponent{
title:string="Hello from SEED!!";
}
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
CopyRight@SeedInfotech ...-----CopyRightComponent
title.component.html/css/ts
courses.component.html/css/ts
copyright.component.html/css/ts
___________________________________________________________________
Angular Module
---------------
-In ANgular,Module is a group of related components,directives,pipes & services
-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],
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
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>
<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>!!
___________________________________________________________________
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]
so use
templateUrl-external html file
template-inline html code
Nested Components
-----------------
here we will create 2 components
parent-comp & child-comp
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
_______________________________________________________
Lab1)create a Greeting component using inline html & css
which prints
Welcome to the world of Angular!!!
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
<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
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
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)
Day 8
------
In the previous session we learnt
Angular Directive
-----------------
1)Component--->tag with a template
<product-info></product-info>
switch(x){
case 1:hjhjhgjhgj
case 2:hjhjhjhgjhg
....
default:hjhgjhgj
}
_____________________________________________________________
Lab1) OrderComponent
OUTPUT
Order Summary
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"}}
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]
<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>
_____________________________________________________________
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
{{75|number|currency}}
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>
____________________________________________________________
hint:-
transform(value:string):string{
if(value=='India')
return 'IND';
else if(value=='Australia')
return 'AUS';
............
}
_____________________________________________________________
Day 9
------
Directives
----------
1)Component
<h1 *ngIf="show">hello</h1>
<h1 *ngFor="let t of arr">hello {{t}}</h1>
<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}"
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]
.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
__________________________________________________________
@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{..}
Custom Directive
-----------------
steps:-
1) Create a class decorated with @Directive({}) in the file
<directive_name>.directive.ts
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]
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 []
___________________________________________________________
**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
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
<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
<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
---------------------
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
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>
#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
{{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
<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.
___________________________________________________________
code activity
-------------
parent-comp----->x
child-comp------->@Input() y
<child-comp [y]="x"></child-comp>
___________________________________________________________
challenge lab
-------------
create a mobilecomponent (to understand binding)
dropdown holding mobile modelnames
button-show details
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
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>
<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
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
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
HttpClientModule---->HttpClient service----->get(url)---->returns an
Observables--->subscribe
methods
get/post/put/delete
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
-----------------------------------------------------
**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() {
}
First run class demo on your PC & edit it to show workshop data
output:-
button fetch data
table/error message
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
second.component.ts
second.component.html
second.component.css
submodule.module.ts
steps:-
1)create a file named submodule.module.ts
Lab1)
create 2 user-defined modules
SubModule1--->FirstComponent,SecondComponent
SubModule2--->ThirdComponent,FourthComponent
@Output decorator
-----------------
used to pass/emit custom event from child to parent
code activity
-----------------
parent-comp--->check(str)
child-comp--->myevent
eg:-
@Output() eventObj=new EventEmitter<string>();
<dictchild-comp (eventObj)="onwordchange($event)">
</dictchild-comp>
______________________________________________________________
Lab2)
pass cityname from child &
print following details in parent
hint:-
if(this.arr[i].cityname==city){
imagepath="assets/images/"+city+".jpg";
}
____________________________________________________________
___________________________________________________________________
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.