Angular - 9-1
Angular - 9-1
Angular-9
Syllabus:
➢ Components
➢ Services
➢ Directives
➢ Pipes
➢ Lifecycle hooks
➢ Communication between components
➢ Unit-test cases
➢ Integration
➢ Interceptors
➢ Forms
➢ Angular Material
➢ Behaviour subject
➢ Single Page Application
➢ Lazy loading
➢ Crud Operations
➢ Mini Project
Angular-9
Commands
Ng s -o
➢ Switch to project
Cd <project-name>
Node <server-file.js>
I.Introduction
Website : https://nodejs.org/en/download/
file : node-v12.16.1-x64.msi
3) install Angular9
1) e2e
2) node_modules:
3) src/app:
Ex.
4) src/app/app.module.ts
5) src/assets:
Ex.
o images
o multimedia files
o xml files
o json files
6) environments:
7) src/favicon.ico:
8) src/index.html:
9) src/main.ts:
10) src/polyfills.ts:
Ex.
Chrome, Mozilla…etc
11) src/styles.css:
12) src/test.ts:
14) angular.json:
=> jQuery
=> BootStrap
=> ReactJS
16) karma.conf.js:
17) package.json:
18) tsconfig.app.json:
Ex.
19) tsconfig.json:
20) tsconfig.spec.json:
➢ this file is the controlling file for all unit test cases
present in angular project.
21) tslint.json:
Chapter-1(Components)
Components:
Example:
Directory Structure:
*****************************************
firstApp
src
app
first.component.ts
first.component.html
app.module.ts
index.html
*****************************************
First.component.ts:
Code:
@Component({
selector:"first",
templateUrl:"./first.component.html"
})
private mean:string;
private mern:string;
private mevn:string;
constructor(){
};
public getMeanData():string{
return this.mean;
};
public getMernData():string{
return this.mern;
};
public getMevnData():string{
return this.mevn;
};
};
First.component.html
Code:
<html><body>
App.module.ts:
Code:
@NgModule({
declarations: [
AppComponent,firstComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [firstComponent]
})
Index.html
<!doctype html>
<html lang="en">
<head>
<base href="/">
</head>
<body>
<first></first>
</body>
</html>
Result:
Angular-9
Chapter-2(Services)
=>Custom Services:
Example:
Directory Structure:
*************************************
serEx
src
app
services
db.service.ts
components
mongodb.component.ts
mongodb.component.html
Angular-9
mysql.component.ts
mysql.component.html
app.module.ts
index.html
************************************
Db.service.ts:
//import Injectable
//use Injectable
@Injectable({
providedIn:"root"
})
//mysqlDB()
public mysqlDB():string{
};
Angular-9
//mongodb()
public mongodb():string{
};
};
Mangodb.component.ts:
//import dbService
//use Component
@Component({
selector:"mongodb",
templateUrl:"./mongodb.component.html"
})
private result:string;
//dependency injection
constructor(private obj:dbService){}
//ngOnInit()
ngOnInit(){
this.result = this.obj.mongodb();
};
Mangodb.component.html:
<html>
<body>
Mysql.component.ts:
@Component({
selector:"mysql",
templateUrl:"./mysql.component.html"
Angular-9
})
private result:string;
constructor(private obj:dbService){}
ngOnInit(){
this.result = this.obj.mysqlDB();
};
Mysql.component.html:
<html>
<body>
<mongodb></mongodb>
</body>
</html>
App.module.ts:
@NgModule({
Angular-9
declarations: [
AppComponent,mysqlComponent,mongodbComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [mysqlComponent]
})
Index.html:
<html>
<body>
<mysql></mysql>
</body>
</html>
Diagrame:
Angular-9
Example:.
Directory structure
***************************************
preSerEx
src
app
services
countries.service.ts
components
countries.component.ts
countries.component.html
app.module.ts
index.html
***************************************
countries.service.ts:
//import Injectable
//import HttpClient
//import Observable
Angular-9
//use Injectable
@Injectable({
providedIn:"root"
})
//dependency injection
constructor(private obj:HttpClient){}
public getCountries():Observable<any>{
return
this.obj.get("https://restcountries.eu/rest/v2/all");
};
};
Angular-9
countries.component.ts:
//import Component
//import countriesService
//import HttpErrorResponse
//use Component
@Component({
selector:"countries",
templateUrl:"./countries.component.html"
})
private result:any;
//dependency injection
constructor(private obj:countriesService){}
ngOnInit(){
this.obj.getCountries().subscribe((posRes)=>{
this.result = posRes;
},(errRes:HttpErrorResponse)=>{
console.log(errRes);
});
}; };
countries.component.html
<!--
@name
@capital
@region
Angular-9
@population
@flag
-->
<table border="1"
cellpadding="10px"
cellspacing="10px"
align="center">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Capital</th>
<th>Region</th>
<th>Population</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
<td>{{i+1}}</td>
<td>{{x.name}}</td>
<td>{{x.capital}}</td>
Angular-9
<td>{{x.region}}</td>
<td>{{x.population}}</td>
</tr>
</tbody>
</table>
App.module.ts:
@NgModule({
declarations: [
AppComponent,countriesComponent
],
imports: [
BrowserModule,HttpClientModule
],
providers: [],
bootstrap: [countriesComponent]
Angular-9
})
index.html:
<body>
<countries></countries>
</body>
Result:
Angular-9
Chapter-3(Integration)
Java Integration
URL :
http://localhost:9090/EmployeeDetailRestResource/api/empService/
getAll
-------------------------------------------------------
1) Tomcat
2) Ecilipse
3) jdk
1) VisualStudio 2015
Example
Directory Structure:
*******************************************************
seriesAndParallelCallsEx
src
app
services
java.service.ts
dotnet.service.ts
components
series.component.ts
series.component.html
Angular-9
parallel.component.ts
parallel.component.html
app.module.ts
index.html
*********************************************************
Commands:
Java.service.ts:
@Injectable({
providedIn: 'root'
})
constructor(private http:HttpClient) { }
Angular-9
public getEmployees():Observable<any>{
return
this.http.get("http://localhost:9090/EmployeeDetailRestResource/
api/empService/getAll");
Dotnet.service.ts:
@Injectable({
providedIn: 'root'
})
constructor(private http:HttpClient) { }
public getEmployees():Observable<any>{
return this.http.get("http://localhost:14741/api/Home");
};
Series.component.ts:
@Component({
selector: 'series',
templateUrl: './series.component.html',
styles: []
})
public javaResult:any;
public dotnetResult:any;
constructor(private java:JavaService,
private dotnet:DotnetService) { }
}else{
};
ngOnInit() {
this.java.getEmployees().subscribe((posRes)=>{
this.javaResult = posRes;
Angular-9
/*************************************************/
this.dotnet.getEmployees().subscribe((posRes)=>{
this.dotnetResult = posRes;
},this.errCallBack);
/*************************************************/
},this.errCallBack);
}; }
Series.component.html:
app.module.ts:
@NgModule({
declarations: [
AppComponent,
SeriesComponent,
ParallelComponent
Angular-9
],
imports: [
BrowserModule,HttpClientModule
],
providers: [],
bootstrap: [SeriesComponent]
})
Index.html:
<body>
<series></series>
</body>
Parallel.component.ts:
@Component({
selector: 'parallel',
templateUrl: './parallel.component.html',
styles: []
Angular-9
})
public javaResult:any;
public dotnetResult:any;
constructor(private java:JavaService,
private dotnet:DotnetService) { }
}else{
};
ngOnInit() {
Observable.forkJoin([
this.java.getEmployees(),
this.dotnet.getEmployees()
]).subscribe((posRes)=>{
this.javaResult = posRes[0];
this.dotnetResult = posRes[1];
},this.errCallBack);
}
Angular-9
};
Parallel.component.html
<h4>{{javaResult | json}}</h4>
<h4>{{dotnetResult | json}}</h4>
app.module.ts
@NgModule({
declarations: [
AppComponent,
SeriesComponent,
ParallelComponent
],
imports: [
BrowserModule,HttpClientModule
],
providers: [],
Angular-9
bootstrap: [ParallelComponent]
})
Index.html
<body>
<parallel></parallel>
</body>
Result:
Angular-9
Chapter-4(Interceptors)
---------------------------------------
step 1.
install SQLServer.
step 2.
***************************
user : sa
password: 123
server : localhost
database: auth
table : login_details
***************************
step 3.
step 4.
> cd InterceptorsEx
step 5.
=> express
=> body-parser
=> cors
Angular-9
step 6.
****************************
interceprotsEx
server
server.js
****************************
step 7.
> cd server
step 8.
step 9.
*********************************************
interceptorsEx
src
app
Interceptor
token.Interceptor.ts
*********************************************
"token.Interceptor.ts" used to add the nareshit as header to req.
step 10.
******************************************
interceprorsEx
src
app
services
login.service.ts
******************************************
step 11.
step 12.
step 13.
Terminal-1
----------
> cd interceprorsEx/server
Terminal-2
----------
> cd interceprorsEx
> ng s -o
Server.js:
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use(cors());
next();
}else{
Angular-9
res.send({"message":"unauthorized user"});
app.post("/login",[checkHeaders],(req,res)=>{
mssql.connect({
user:"sa",
password:"123",
database:"auth",
server:"localhost"
},(err)=>{
else{
(err,records)=>{
else{
if(records.recordset.length>0){
res.send({"login":"success"});
Angular-9
}else{
res.send({"login":"fail"});
})
});
});
app.listen(8080);
token.interceptor.ts:
import { HttpRequest,
HttpHandler,
@Injectable({
providedIn:"root"
})
intercept(req:HttpRequest<any>,
handler:HttpHandler):Observable<HttpEvent<any>>{
setHeaders:{
"token":"naresh"
});
return handler.handle(req1);
};
Login.service.ts:
@Injectable({
providedIn: 'root'
})
constructor(public http:HttpClient) { }
public authenticate(data:any):Observable<any>{
return this.http.post("http://localhost:8080/login",data);
};
Angular-9
};
Login.component.ts:
@Component({
selector: 'login',
templateUrl: './login.component.html',
styles: []
})
public result:any;
constructor(public service:LoginService) { }
ngOnInit() {
public login(data:any):any{
this.service.authenticate(data)
.subscribe((posRes)=>{
this.result = posRes;
},(errRes:HttpErrorResponse)=>{
}else{
});
};
};
Login.component.html
<fieldset>
<legend>Login</legend>
<input type="text"
name="uname"
placeholder="user name"
[(ngModel)]="uname">
<br><br>
<input type="password"
name="upwd"
placeholder="password"
[(ngModel)]="upwd">
<br><br>
<button (click)="login({'uname':uname,'upwd':upwd})">
Login
</button>
Angular-9
<h1>{{result | json}}</h1>
</fieldset>
app.module.ts:
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,HttpClientModule,FormsModule
],
providers: [{
provide:HTTP_INTERCEPTORS,
useClass:tokenInterceptor,
Angular-9
multi:true
}],
bootstrap: [LoginComponent]
})
Index.html:
<body>
<login></login>
</body>
Angular-9
Chapter-5( Directives )
=>Pre-defined directives
1. ngFor
2. ngif
3. (click)
4. (dbclick)
5. [(ngmodel)]
6. (ngsubmit)
7. [ngclass]
8. [ngstyle]
9. [ngswitch]
• Directives are categorized into three types
o Structural type directives
o Event type directives
o Attribute type directives
• Structural type directives have manipulate into dom
• Structural type directives starts with “*”
• Based on the requirement we are adding or removing dom elements
from browser memory.
Angular-9
• In order to handle events raised by dom ,we are using event type
directives.
• Event type directives are serounder with “()”
• Attribute type directives serounder with ”[]”
1) *ngFor
Syntax.
constants
---------
1) index
2) first
3) last
4) even
5) odd
2) *ngIf
Example:
Directory Structure:
*****************************************
firstApp
src
app
first.component.ts
first.component.html
app.module.ts
index.html
*****************************************
First.component.ts:
@Component({
selector: 'app-root',
templateUrl: './first.component.html',
styleUrls: ['./first.component.css']
})
title = 'first';
num:number = 0;
Angular-9
clickMe(arg1,arg2){
alert("Login Success");
}else{
alert("Login Fail");
};
First.component.html
<!--
*ngFor
------
-->
<!--
let i = index;
let f = first;
let l = last;
let e = even;
let o = odd;">
Angular-9
<span>{{x}}...{{i}}...{{f}}...{{l}}...{{e}}...{{o}}</span>
</div>
-->
<!--
[ngStyle]
<h1 [ngStyle]="{'color':'red'}">Hello</h1>
<h1
[ngStyle]="{'color':title==='firstApp'?'green':'red'}">Welcome</
h1>
<div [ngSwitch]="x">
</div>
</div>
-->
<!--
Angular-9
[ngClass]
-->
<!--
<h1 [ngClass]="{'text-success':true}">Hello</h1>
<h1 [ngClass]="{'text-danger':title==='firstApp'}">Welcome</h1>
<div [ngSwitch]="x">
</div>
</div> -->
<!--
<div class="container">
<br><br>
Angular-9
(dblclick)="num=num+1"></button>
(dblclick)="num=num-1"></button>
</div>
-->
<fieldset>
<legend>Login</legend>
<input type="text"
placeholder="user name"
#uname>
<br><br>
<input type="password"
placeholder="user password"
#upwd>
<br><br>
<button
(click)="clickMe(uname.value,upwd.value)">Login</button>
</fieldset>
Angular-9
App.module.ts:
@NgModule({
declarations: [
FirstComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [FirstComponent]
})
Index.html:
<body>
<first></first>
</body>
=>Custom Directives:
Example:
Directory Structure:
*****************************************
CustDirex
src
app
my.directive.ts
app.component.ts
app.component.html
app.module.ts
Angular-9
index.html
*****************************************
app.component.html
<br><br>
my.directive.ts
@Directive({
selector: '[myDir]'
})
@Input() var_one;
@Input() var_two;
constructor(public _el:ElementRef) { }
@HostListener("mouseenter") onmouseenter(){
this.changeColor(this.var_one);
};
@HostListener("mouseleave") onmouseleave(){
Angular-9
this.changeColor(this.var_two);
};
public changeColor(arg1){
this._el.nativeElement.style.backgroundColor=arg1;
app.module.ts:
@NgModule({
declarations: [
AppComponent,
myDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
Angular-9
Index.html:
<body>
<app></app>
</body>
Example:
Directory Structure:
*****************************************
CustDirex
src
app
strl.directive.ts
Angular-9
app.component.ts
app.component.html
app.module.ts
index.html
*****************************************
app.component.html
<h1 *hello="false">Welcome</h1>
strl.directive.ts
@Directive({
selector: '[hello]'
})
constructor(public _templateRef:TemplateRef<any>,
public _viewContainerRef:ViewContainerRef) { }
if(arg1){
this._viewContainerRef.createEmbeddedView(this._templateRef)
}else{
this._viewContainerRef.clear();
}; } };
Angular-9
App.module.ts:
@NgModule({
declarations: [
AppComponent,
StrlDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
Index.html:
<body>
<app-root></app-root>
</body>
Angular-9
@Input
@Output
----------------------------------------------------------------
********************************
child.component.ts
child.component.html
********************************
Angular-9
******************************
parent.component.ts
parent.component.html
******************************
Example:
Directory Structure:
*****************************************
Combtcom
src
app
child.component.ts
child.component.html
parent.component.ts
parent.component.html
app.module.ts
index.html
*****************************************
Angular-9
child.component.ts
@Component({
selector:"child",
templateUrl:"./child.component.html"
})
export class childComponent{
@Input() p_id;
@Input() p_name;
@Input() p_cost;
@Output() send:EventEmitter<any> = new EventEmitter();
clickMe():any{
this.send.emit(this.p_id+"...."+this.p_name+"...."+this.p_cost
)
};
};
child.component.html
<h2>Product ID:<span style="color: red;">{{p_id}}</span></h2>
<h2>Product Name:<span style="color:
red;">{{p_name}}</span></h2>
<h2>Product Cost:<span style="color:
red;">{{p_cost}}</span></h2>
<button (click)="clickMe()">Send</button>
<hr>
parent.component.ts
import { Component } from "@angular/core";
@Component({
Angular-9
selector:"parent",
templateUrl:"./parent.component.html"
})
export class parentComponent{
private products:Array<any> = [
{p_id:111,p_name:"p_one",p_cost:10000},
{p_id:222,p_name:"p_two",p_cost:20000},
{p_id:333,p_name:"p_three",p_cost:30000},
{p_id:444,p_name:"p_four",p_cost:40000},
{p_id:555,p_name:"p_five",p_cost:50000}
];
public myFun(data:any){
alert(data);
}
};
parent.component.html
<child
[p_id]="x.p_id"
[p_name]="x.p_name"
[p_cost]="x.p_cost"
(send)="myFun($event)"
*ngFor="let x of products"></child>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { parentComponent } from './parent.component';
import { childComponent } from './child.component';
Angular-9
@NgModule({
declarations: [
AppComponent,parentComponent,childComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [parentComponent]
})
export class AppModule { }
index.html
<body>
<parent></parent>
</body>
----------------------------------------------------------------
********************************
second.component.ts
second.component.html
********************************
Angular-9
******************************
first.component.ts
first.component.html
******************************
Example:
Directory Structure:
*****************************************
Combtcom
src
app
first.component.ts
first.component.html
second.component.ts
second.component.html
app.module.ts
index.html
*****************************************
first.component.ts
@Component({
selector:"first",
Angular-9
templateUrl:"./first.component.html"
})
/*
@ViewChild(secondComponent,{static:true})
private second:secondComponent;
clickMe(){
this.second.var_one = "welcome_1";
this.second.var_two = "welcome_2";
};
*/
@ViewChildren(secondComponent)
ngAfterViewInit(){
this.arr = this.obj.toArray();
};
clickMe(){
this.arr.forEach((element,index)=>{
element.var_one = "welcome_1";
element.var_two = "welcome_2";
});
Angular-9
};
};
first.component.html
<second></second>
<second></second>
<second></second>
<button (click)="clickMe()">Change</button>
second.component.ts
@Component({
selector:"second",
templateUrl:"./second.component.html"
})
public var_one:string;
public var_two:string;
constructor(){
this.var_one = "hello_1";
this.var_two = "hello_2";
};
};
second.component.html
app.module.ts
index.html
<body>
<first></first>
</body>
Chapter-7( Pipes )
=>predefined pipes
➢ uppercase
➢ lowercase
➢ titlecase
➢ currency
➢ json
➢ slice
➢ number
➢ percent
➢ async
➢ date
1) uppercase
2) lowercase
3) titlecase
4) currency
5) json
6) slice
7) number/decimal
8) percent
9) async
10) date
ng g p message --skipTests
Angular-9
=>Custom Pipes
Example:
Directory Structure:
*****************************************
pipesex
src
app
reverse.pipe
message.pipe
app.component.ts
app.component.html
app.module.ts
index.html
*****************************************
app.component.html
<h1>{{“hello” | reverse}}</h1>
<h1>{{“hello” | reverse}}</h1>
reverse.pipe
@Pipe({
name: 'reverse'
})
Angular-9
return Array.from(value).reverse().join("");
message.pipe
@Pipe({
name: 'message'
})
app.component.html
{{"Angular9" | message:"to":"welcome"}}
</h1>
<!--
-->
<h1>{{var_ten | async}}</h1>
<h1>{{var_nine | date:"fullDate"}}</h1>
<h1>{{var_nine | date:"medium"}}</h1>
<h1>{{var_nine | date:"short"}}</h1>
<h1>{{var_nine | date:"dd-MMM-yyyy"}}</h1>
<h1>{{var_nine | date:"dd-MM-yy"}}</h1>
<h1>{{var_eigth | percent}}</h1>
<h1>{{var_seven | number:"4.1-2"}}</h1>
<h1>{{var_seven | number:"3.2-3"}}</h1>
<h1>{{var_six | slice:2:-3}}</h1>
<h1>{{var_six | slice:2:-1}}</h1>
<h1>{{var_six | slice:2:5}}</h1>
<h1>{{var_six | slice:2:4}}</h1>
<h1>{{var_five | json}}</h1>
<h1>{{var_four | currency:"INR"}}</h1>
<h1>{{var_four | currency:"EUR"}}</h1>
<h1>{{var_four | currency:"GBP"}}</h1>
<h1>{{var_four | currency}}</h1>
<h1>{{var_three | titlecase}}</h1>
<h1>{{var_two | lowercase}}</h1>
<h1>{{var_one | uppercase}}</h1>
Angular-9
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
private var_one:string="hello";
private var_four:number=100;
private var_five:any={
p_id:111,
p_name:"p_one",
p_cost:10000
};
private var_six:Array<number>=[
10,20,30,40,50
];
private var_seven:number=100.12345;
Angular-9
private var_ten:any;
constructor(){
setTimeout(()=>{
resolve("Success");
},5000);
});
};
app.module.ts
@NgModule({
declarations: [
AppComponent,
ReversePipe,
MessagePipe
Angular-9
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
index.html
<body>
<app-root></app-root>
</body>
Angular-9
2) ngOnInit()
3) ngDoCheck()
4) ngAfterContentInit()
5) ngAfterContentChecked()
6) ngAfterViewInit()
7) ngAfterViewChecked()
8) ngOnDestroy()
Example:
Directory Structure:
*****************************************
lifecyclehoks
src
app
app.component.ts
app.component.html
app.module.ts
index.html
*****************************************
app.component.ts
@Component({
selector: 'app-root',
Angular-9
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
constructor(){
console.log("--in constructor--");
};
ngOnChanges(){
console.log("--in ngOnChanges--");
};
ngOnInit(){
console.log("--in ngOnInit--");
};
public increment():number{
return this.num+=100;
};
public decrement():number{
return this.num-=100;
};
ngDoCheck(){
console.log("--in ngDoCheck--");
};
ngAfterContentInit(){
console.log("--in ngAfterContentInit--");
};
ngAfterConetentChecked(){
Angular-9
console.log("--in ngAfterContentChecked--");
};
ngAfterViewInit(){
console.log("--in ngAfterViewInit--");
};
ngAfterViewChecked(){
console.log("--in ngAfterViewCheck--");
};
ngOnDestroy(){
console.log("--in ngOnDestroy--");
};
};
Angular-9
app.component.html
<h1>{{num}}</h1>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
index.html
<body>
<app-root></app-root> </body>
Angular-9
Chapter-9 ( Forms )
Example:
Directory Structure:
*****************************************
tdfex
src
app
components
tdf.component.ts
tdf.component.html
app.module.ts
index.html
tdf.component.ts
@Component({
selector: 'tdf',
templateUrl: './tdf.component.html',
styleUrls: ['./tdf.component.css']
})
export class TdfComponent implements OnInit {
constructor() { }
ngOnInit() {
}
register(data:any){
console.log(data);
}}
tdf.component.html
<!--
Directives in TDF
1) ngForm
- this directive helps assign the logical name to forms.
2) ngModel
- this directive behaves like one way data binding
directive.
3) ngModelGroup
Angular-9
<body>
<form #profileData="ngForm"
(ngSubmit)="register(profileData.value)">
<table>
<tr>
<td>User Name</td>
<input type="text" name="uname" ngModel>
</tr>
<tr>
<td>Password</td>
<input type="password" name="upwd" ngModel>
</tr>
<tr>
<td>Age</td>
<input type="number" name="age" ngModel>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio"
Angular-9
name="gender"
value="male"
ngModel>Male</td>
<td><input type="radio"
name="gender"
value="female"
ngModel>Female</td>
</tr>
<tr ngModelGroup="addr">
<td>City</td>
<td>
<input type="text"
name="ucity"
ngModel>
</td>
</tr>
<tr>
<td>Country</td>
<td><select name="ucountry" ngModel>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
Angular-9
</table>
</form>
</body>
app.module.ts
@NgModule({
declarations: [
AppComponent,
TdfComponent
],
imports: [
BrowserModule,FormsModule
],
providers: [],
bootstrap: [TdfComponent]
})
export class AppModule { }
index.html
<body>
<tdf></tdf>
</body>
Angular-9
Example:
Directory Structure:
*****************************************
mdfex
src
app
app.component.ts
app.component.html
app.module.ts
index.html
*****************************************
app.component.ts
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
profileData:FormGroup;
constructor(){
this.profileData = new FormGroup({
uname : new
FormControl("Naresh",[Validators.required,
Validators.minLength(3),
Validators.maxLength(6)]),
addr : new FormGroup({
address : new FormControl()
}),
gender : new FormControl(),
country : new FormControl()
});
}
register():any{
console.log(this.profileData.value);
};
};
app.component.html
<label>Uname</label>
<input type="text"
name="uname"
class="form-control"
formControlName="uname"
required>
</div>
<div *ngIf="profileData.controls['uname']
.hasError('required')"
class="alert alert-danger">
**** can't left blank ****
</div>
<div *ngIf="profileData.controls['uname']
.hasError('minlength')"
class="alert alert-danger">
**** minimum 3 characters are required ****
</div>
<div
*ngIf="profileData.controls['uname'].hasError('maxlength')"
class="alert alert-danger">
**** maximum 6 characters are allowed ****
</div>
class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label>Gender</label>
<input type="radio"
class="form-control"
name="gender"
value="male"
formControlName="gender">Male
<input type="radio"
class="form-control"
name="gender"
value="female"
formControlName="gender">Female
</div>
<div class="form-group">
<label>Country</label>
<select name="country"
class="form-control"
formControlName="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="japan">Japan</option>
<option value="china">China</option>
</select>
</div>
Angular-9
</form>
</div>
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Angular-9
index.html
<body>
<app-root></app-root>
</body>
Angular-9
Example:
Directory Structure:
*****************************************
angmatex
src
app
app.component.ts
app.component.html
app.module.ts
index.html
*****************************************
app.component.html
<br><br>
<div class="mat-elevation-z8">
<ng-container matColumnDef="p_id">
</ng-container>
Angular-9
<ng-container matColumnDef="p_name">
</ng-container>
<ng-container matColumnDef="p_cost">
</ng-container>
</table>
</div>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
Angular-9
})
@ViewChild(MatPaginator,{static:true})
public paginator:MatPaginator;
@ViewChild(MatSort,{static:true})
public sort:MatSort;
public data:MatTableDataSource<any>;
constructor(){
{"p_id":111,"p_name":"p_one","p_cost":10000},
{"p_id":555,"p_name":"p_five","p_cost":50000},
{"p_id":222,"p_name":"p_two","p_cost":20000},
{"p_id":444,"p_name":"p_four","p_cost":40000},
{"p_id":333,"p_name":"p_three","p_cost":30000}
]); };
ngOnInit(){
this.data.paginator = this.paginator;
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatTableModule,
MatPaginatorModule,
MatSortModule
],
providers: [],
bootstrap: [AppComponent]
})
index.html
<body>
<app-root></app-root> </body>
Angular-9
> ng test
Example:
Directory Structure:
*****************************************
unittestex
src
app
app.component.ts
app.component.html
calc.spec
calc
app.module.ts
index.html
*****************************************
app.component.ts
@Component({
selector: 'app-root',
Angular-9
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
title = 'unitTestCasesEx';
calc.spec
/*
*/
describe("calculator testing",()=>{
let obj:Calculator;
/*
beforeEach(()=>{
});
*/
/*
*/
beforeAll(()=>{
});
/*
*/
/*
*/
/*
*/
expect(result).toBe(20);
});
});
expect(result).toBe(0);
});
});
describe("array testing",()=>{
it("check 30 in my_array",()=>{
expect(obj.my_array).toContain(30);
});
});
});
Calc:
public add(num1:number,
num2:number):number{
return num1+num2;
};
public sub(num1:number,
num2:number):number{
return num1-num2;
};
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
index.html
<body>
<app-root></app-root>
</body>
Angular-9
Chapter-12( BehaviorSubject )
Example:
Directory Structure:
*******************************************
bahaviourSubEx
src
app
services
test.service.ts
components
first.component.ts
first.components.html
second.component.ts
second.component.html
app.module.ts
index.html
*********************************************
Angular-9
test.service.ts
@Injectable({
providedIn:"root"
})
public changeData(arg1:string){
this.data.next(arg1);
};
};
first.component.ts
@Component({
selector:"first",
templateUrl:"./first.component.html"
})
private result:string;
constructor(private service:testService){}
ngOnInit(){
this.service.cast.subscribe((posRes)=>{
this.result = posRes;
});
};
clickMe(arg1){
this.service.changeData(arg1);
};
};
first.components.html
<h1>{{result}}</h1>
<button (click)="clickMe(msg.value)">Change</button>
second.component.ts
@Component({
selector:"second",
templateUrl:"./second.component.html"
})
Angular-9
private result:string;
constructor(private service:testService){}
ngOnInit(){
this.service.cast.subscribe((posRes)=>{
this.result = posRes;
});
};
};
second.component.html
<h1>{{result}}</h1>
app.module.ts
@NgModule({
declarations: [
AppComponent,firstComponent,secondComponent
],
imports: [
Angular-9
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
index.html
<body>
<app-root></app-root>
</body>
Angular-9
Diagram:
Angular-9
step 1.
step 2.
step 3.
step 4.
src
app
routes
app.routes.ts
********************************
Angular-9
step 5.
-------------------------------
step 6.
step 7.
step 8.
=> /child_one
=> /child_two
=> /child_three
step 9.
step 10.
------------------------------------------------------
step 11.
Routing Guards
--------------
1) CanActivate
2) CanDeactivate
3) CanActivateChild
Example:
Directory Structure:
*****************************************
spademoex
src
app
components
page_one.component.html
page_one.component.ts
page_two.component.html
page_two.component.ts
page_three.component.html
page_three.component.ts
child_one.component.html
child_one.component.ts
child_two.component.html
child_two.component.ts
child_three.component.html
child_three.component.ts
index.component.html
index.component.ts
guards
auth.guards.ts
routings
app.routes.ts
app.module.ts
index.html
*****************************************
Angular-9
page_one.component.html
<p>page-one works!</p>
<h1 style="color: black;margin-right:100px;">{{var_one}}</h1>
<a [routerLink]="['childone']" ><b>Child_one</b></a>
<router-outlet></router-outlet>
page_one.component.ts
@Component({
selector: 'pageone',
templateUrl: './page-one.component.html',
styles: []
})
export class PageOneComponent implements OnInit {
private var_one:any;
constructor(public route:ActivatedRoute) {
this.var_one=this.route.snapshot.params["p_id"]+"....."+
this.route.snapshot.params["p_name"]+"...."+
this.route.snapshot.params["p_cost"];
}
ngOnInit() {
}
}
Angular-9
page_two.component.html
<p>page-two works!</p>
<h1 style="color: blue;margin-right:100px;">{{var_two}}</h1>
<a [routerLink]="['childtwo']" ><b>Child_two</b></a>
<router-outlet></router-outlet>
page_two.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'pagetwo',
templateUrl: './page-two.component.html',
styles: []
})
export class PageTwoComponent implements OnInit {
private var_two:any;
constructor() {
this.var_two="Welcome to pagetwo............!"
}
ngOnInit() {
}}
page_three.component.html
<p>page-two works!</p>
<h1 style="color: blue;margin-right:100px;">{{var_two}}</h1>
<a [routerLink]="['childtwo']" ><b>Child_two</b></a>
<router-outlet></router-outlet>
page_three.component.ts
@Component({
Angular-9
selector: 'pagethree',
templateUrl: './page-three.component.html',
styles: []
})
export class PageThreeComponent implements OnInit {
private var_three:any;
constructor() {
this.var_three="welcome to page three.......!";
}
ngOnInit() {
}}
Index.component.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-light navbar-
light">
<ul class="navbar-nav">
<li class="nav-item active">
</li>
<li class="nav-item">
Angular-9
</li>
<li class="nav-item">
</li>
</ul>
</nav>
<!--
<a [routerLink]="['/pageone']" style="margin-right:
100px;">PageOne</a>
<a [routerLink]="['/pagetwo']" style="margin-right:
100px;">Pagetwo</a>
<a [routerLink]="['/pagethree']" style="margin-right:
100px;">Pagethree</a>
-->
<router-outlet></router-outlet>
</body>
</html>
child_one.component.html
<h1 style="color: springgreen;">{{var_four}}</h1>
child_one.component.ts
import { Component } from '@angular/core';
Angular-9
@Component({
selector:"childone",
templateUrl:'./child-one.component.html'
})
export class childonecomponent
{
private var_four:any;
constructor(){
this.var_four="Welcome to child_one component";
}
}
child_two.component.html
<h1 style="color: tomato;">{{var_five}}</h1>
child_two.component.ts
import { Component } from '@angular/core';
import { ThrowStmt } from '@angular/compiler';
@Component({
selector:"childtwo",
templateUrl:"./child-two.component.html"
})
export class childtwocomponent
{
private var_five:any;
constructor(){
this.var_five="Welcome to child_two component";
}
}
child_three.component.html
<h1 style="color: violet;">{{var_six}}</h1>
Angular-9
child_three.component.ts
@Component({
selector:"childthree",
templateUrl:"./child-three.component.html"
})
private var_six:any;
constructor(){
}}
app.routes.ts
{path:"pageone/:p_id/:p_name/:p_cost",component:PageOneComponent
,
children:[{path:"childone",component:childonecomponent}],
canActivate:[authGuards]},
{path:"pagetwo",component:PageTwoComponent,
children:[{path:"childtwo",component:childtwocomponent}],
canDeactivate:[authGuards]},
{path:"pagethree",component:PageThreeComponent,
children:[{path:"childthree",component:childthreecomponent}],
canActivateChild:[authGuards]}
];
auth.guards.ts
@Injectable({
providedIn:"root"
})
canActivate():boolean{
};
canDeactivate():boolean{
};
canActivateChild():boolean{
};};
App.module.ts
@NgModule({
declarations: [
AppComponent,
PageOneComponent,
IndexComponent,
PageTwoComponent,
PageThreeComponent,
childonecomponent,
childtwocomponent,
childthreecomponent
],
imports: [
BrowserModule,RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [IndexComponent]
})
index.html
Result:
Angular-9
Lazy-loading
Diagram:
step 1.
IndexComponent
PageoneComponent
step 2.
- CountriesComponent
- CountriesService
- CountriesModule
step 3.
step 4.
Directory structure(Main)
************************************************
spaDemo2
src
app
index.component.html
index.component.ts
pageone.component.html
pageone.component.ts
**********************************************
Angular-9
*******************************************************
spaDemo2
src
app
countries.service.ts
countries.component.ts
countries.component.html
countries.module.ts
******************************************************
Directory structure:
********************************************************
spaDemo2
src
app
auth.guard.ts
Angular-9
*******************************************************
PageoneComponent to IndexComponent 1
CountriesModule to IndexComponent 2
app.routes.ts
index.component.html
<a [routerLink]="['/lazy']"><b>Lazy</b></a>
<br><br>
<router-outlet></router-outlet>
index.component.ts
@Component({
selector:"index",
templateUrl:"./index.component.html"
})
Angular-9
pageone.component.html
pageone.component.ts
@Component({
selector:"page_one",
templateUrl:"./pageone.component.html"
})
public var_one:string;
constructor(){
};
};
countries.service.ts
@Injectable({
providedIn:"root",
})
Angular-9
constructor(public http:HttpClient){}
public getCountries():Observable<any>{
return
this.http.get("https://restcountries.eu/rest/v2/all");
};
};
countries.component.ts
@Component({
selector:"countries",
templateUrl:"./countries.component.html"
})
public result:any;
constructor(public service:CountriesService){}
ngOnInit(){
this.service.getCountries().subscribe((posRes)=>{
this.result = posRes;
},(errRes:HttpErrorResponse)=>{
Angular-9
}else{
});
countries.component.html
<table border="1"
cellpadding="10px"
cellspacing="10px"
align="center">
<tr>
<th>SNO</th>
<th>NAME</th>
<th>CAPITAL</th>
<th>POPULATION</th>
<th>REGION</th>
<th>NATIVENAME</th>
<th>FLAG</th>
Angular-9
</tr>
</thead>
<tbody>
<td>{{i+1}}</td>
<td>{{x.name}}</td>
<td>{{x.capital}}</td>
<td>{{x.population}}</td>
<td>{{x.region}}</td>
<td>{{x.nativeName}}</td>
</tr>
</tbody>
</table>
countries.module.ts
//import NgModule
//import CountriesComponent
//import CountriesService
Angular-9
//import HttpClientModule
//import CommonModule
//import RouterModule
@NgModule({
declarations:[CountriesComponent],
imports:[HttpClientModule,
CommonModule,
RouterModule.forChild([{path:"",component:CountriesComponent}])]
,
providers:[CountriesService],
exports:[CountriesComponent]
})
auth.guard.ts
@Injectable({
providedIn:"root"
Angular-9
})
canLoad():boolean{
};
app.module.ts
@NgModule({
declarations: [
AppComponent,IndexComponent,PageoneComponent
],
imports: [
BrowserModule,lazyRoutes
],
providers: [],
Angular-9
bootstrap: [IndexComponent]
})
app.routes
//import ModuleWithProviders
// {path:"page_one",component:PageoneComponent},
//
{path:"lazy",loadChildren:"./countries.module#CountriesModule",
// canLoad:[authGuard]}
// ];
{path:"page_one",component:PageoneComponent},
{path:"lazy",
loadChildren:()=>import("./countries.module").then(m=>m.Countrie
sModule),
Angular-9
canLoad:[authGuard]}
];
index.html
<body>
<index></index>
</body>
Angular-9
Chapter-14(Crud Operations)
CRUD Operations:
Example:
Directory Structure:
*****************************************
crudApp
server
server.js
src
app
components
crud.component.html
crud.component.ts
services
FetchService
InsertService
UpdateService
DeleteService
app.module.ts
index.html
*****************************************
p_cost integer);
******************************
host : localhost
user : root
Password: admin
database: angular7am
table : products
*******************************
> cd crudApp
Angular-9
=> express
=> mysql
=> cors
=> body-parser
**************************
crudApp
server
server.js
**************************
server.js:
//connect to database
connection.connect();
//delete request
app.post("/delete",(req,res)=>{
connection.query(`delete from products where p_id=${req.body.p_id}`,(err,resu
lt)=>{
if(err) throw err;
else{
res.send({delete:"success"});
}
});
});
//assign the port no
app.listen(8080);
console.log("server listening the port no.8080");
> cd server
=> FetchService
=> InsertService
=> UpdateService
=> DeleteService
=> Fetch.Service.ts
=> Insert.Service.ts
=> Delete.Service.ts
Crud.component.ts
ngOnInit() {
this.fetch.getProducts().subscribe((posRes)=>{
this.result = posRes;
},this.errCallBack);
Angular-9
deleteRecord(data):any{
console.log(data);
this.remove.deleteRecord({p_id:data})
.subscribe((posRes)=>{
if(posRes.delete === "success"){
let i =
this.result
.findIndex((element,index)=>{
return element.p_id === data;
});
this.result.splice(i,1);
}else{
alert("delete fail");
}
},this.errCallBack);
}
openUpdateModal(id: string,data:any) {
this.bodyText = data;
console.log(this.bodyText);
this.update_pid=data.p_id;
this.update_pname=data.p_name;
this.update_pcost=data.p_cost;
this.service.open(id);
}
closeUpdateModal(id: string) {
this.update.updateRecord({"p_id":this.update_pid,"p_name":this.update_pname,"
p_cost":this.update_pcost})
.subscribe((posRes)=>{
if(posRes.update === "success"){
let i = this.result.findIndex((element,index)=>{
return element.p_id == this.update_pid;
});
this.result[i].p_name = this.update_pname;
this.result[i].p_cost = this.update_pcost;
this.service.close(id);
}
},this.errCallBack);
}
Angular-9
cancel(id:string){
this.service.close(id);
}
insertRecord(){
this.service.open("insert");
};
insertR(id,data:any){
this.insert.insertRecord(data)
.subscribe((posRes)=>{
if(posRes.insert === "success"){
this.result.push(data);
}else{
alert("Insert Fail");
}
this.service.close(id);
},this.errCallBack);
}
removeR(id){
this.service.close(id);
}
Crud.component.html
<button class="glyphicon glyphicon-plus
btn btn-success"
(click)="insertRecord()"
style="position: absolute;
right: 0;
padding: 10px;"></button>
<table border="1"
cellpadding="30px"
cellspacing="30px"
align="center"
style="font-size: 20px;
text-align: center;">
<thead style="background-color: gray;">
Angular-9
<tr>
<th>SNO</th>
<th>P_ID</th>
<th>P_NAME</th>
<th>P_COST</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let x of result;let i=index">
<td>{{i+1}}</td>
<td>{{x.p_id}}</td>
<td>{{x.p_name}}</td>
<td>{{x.p_cost}}</td>
<td><button
class="glyphicon glyphicon-edit"
(click)="openUpdateModal('edit',x)"></button></td>
<td><button
class="glyphicon glyphicon-trash"
(click)="deleteRecord(x.p_id)"></button></td>
</tr>
</tbody>
</table>
<jw-modal id="edit">
<h1>Edit</h1>
<p>P_ID: <input type="number"
[(ngModel)]="update_pid" /></p>
<p>P_NAME: <input type="text"
[(ngModel)]="update_pname" /></p>
<p>P_COST: <input type="number"
[(ngModel)]="update_pcost" /></p>
<button (click)="closeUpdateModal('edit');">Update</button>
<button (click)="cancel('edit');">Cancel</button>
</jw-modal>
<jw-modal id="insert">
<h1>Insert</h1>
<p>P_ID: <input type="number"
[(ngModel)]="insert_pid" /></p>
<p>P_NAME: <input type="text"
Angular-9
[(ngModel)]="insert_pname" /></p>
<p>P_COST: <input type="number"
[(ngModel)]="insert_pcost" /></p>
<button (click)="insertR('insert',
{'p_id':insert_pid,
'p_name':insert_pname,
'p_cost':insert_pcost});">Insert</button>
<button (click)="removeR('insert');">Cancel</button>
</jw-modal>
}
Directory
*********************
src
app
_model
********************
app.module.ts
@NgModule({
declarations: [
AppComponent,
CrudComponent
],
imports: [
BrowserModule,HttpClientModule,FormsModule,ModalModule
],
providers: [],
bootstrap: [CrudComponent]
})
export class AppModule { }
openUpdateModal(id: string,data:any) {
this.bodyText = data;
console.log(this.bodyText);
this.update_pid=data.p_id;
this.update_pname=data.p_name;
this.update_pcost=data.p_cost;
this.service.open(id);
}
closeUpdateModal(id: string) {
this.update.updateRecord({"p_id":this.update_pid,
"p_name":this.update_pname,
"p_cost":this.update_pcost})
.subscribe((posRes)=>{
if(posRes.update === "success"){
let i = this.result
.findIndex((element,index)=>{
return element.p_id ==
this.update_pid;
Angular-9
});
this.result[i].p_name =
this.update_pname;
this.result[i].p_cost =
this.update_pcost;
this.service.close(id);
}
},this.errCallBack);
cancel(id:string){
this.service.close(id);
}
Index.html
<body>
<crud></crud>
</body>
Angular-9
Result:
Angular-9
MiniProject Implementation
Angular-9
**************************************
Frontend : Angular
Backend : NodeJS
Database : SQLServer
**************************************
=> login_details
=> about
=> portfolio
=> contact
*******************************************
server : localhost
user : sa
password : 123
database : miniproject
tables : login_details
about
portfolio
contact
*******************************************
Angular-9
3) switch to miniproject
> cd miniproject
=> express
=> mssql
=> body-parser
=> cors
=> jwt-simple
Command:
Directory structure
*************************************
miniproject
server
config
db_properties.js
token.js
generateToken.js
auth.js
login
login.js
about
about.js
portfolio
portfolio.js
contact
contact.js
logout
logout.js
server.js
****************************************
Angular-9
db_properties.js
const obj = {
server : "localhost",
user : "sa",
password : "123",
database : "miniproject"
};
module.exports = obj;
token.js
let obj = {
token : ""
};
module.exports = obj;n.js
Angular-9
generateToken.js
return jwt.encode(data,password);
};
module.exports = genToken;
auth.js
//read headers
next();
}else{
res.send({'message':'unauthorized user'});
Angular-9
};
module.exports = auth;
login.js
.post("/",(req,res)=>{
mssql.connect(require("../config/db_properties"),(err)=>{
else{
else{
if(records.recordset.length>0){
let token =
require("../config/generateToken")({'uname':req.body.uname,
'upwd':req.body.upwd},"[email protected]");
Angular-9
require("../config/token").token = token;
res.send({'login':'success','token':token});
}else{
res.send({'login':'fail'});
mssql.close();
});
});
});
module.exports = login;
about.js
let mssql = require("mssql");
let about = require("express").Router().get("/",
[require("../config/auth")],(req,res)=>{
mssql.connect(require("../config/db_properties"),
(err)=>{
if(err) throw err;
else{
(err,records)=>{
if(err) throw err;
else{
res.send(records);
}
mssql.close();
});
}
});
});
module.exports = about;
portfolio.js
let mssql = require("mssql");
let portfolio = require("express").Router().get("/",
[require("../config/auth")],(req,res)=>{
mssql.connect(require("../config/db_properties"),
(err)=>{
if(err) throw err;
else{
let queryObj = new mssql.Request();
}
mssql.close();
});
}
});
});
module.exports = portfolio;
contact.js
[require("../config/auth")],(req,res)=>{
mssql.connect(require("../config/db_properties"),
(err)=>{
else{
(err,records)=>{
else{
res.send(records);
}
Angular-9
mssql.close();
});
});
});
module.exports = contact;
logout.js
let logout =
require("express").Router()
.get("/",[require("../config/auth")],(req,res)=>{
require("../config/token").token = "";
res.send({logout:"success"});
}else{
res.send({logout:"fail"});
} });
module.exports = logout;
server.js
app.use(cors());
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use("/login",require("./login/login"));
app.use("/about",require("./about/about"));
app.use("/portfolio",require("./portfolio/portfolio"));
app.use("/contact",require("./contact/contact"));
app.use("/logout",require("./logout/logout"));
app.listen(8080);
> cd miniproject
> cd server
************************************************************
AppModule(Main Module)(BootStrap)
LoginModule DashboardModule
- AboutModule
- PortfolioModule
- ContactModule
/************************************************************/
ContactModule
**********************************
src
app
contact
services
contact.service.ts
components
contact.component.ts
contact.component.html
module
contact.module.ts
***********************************
Angular-9
contact.service.ts
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn:"root"
})
export class ContactService{
constructor(private http:HttpClient){}
public getData():Observable<any>{
return this.http.get("http://localhost:8080/contact");
};
};
contact.component.ts
@Component({
selector:"contact",
templateUrl:"./contact.component.html"
})
private result:any;
constructor(private service:ContactService){}
ngOnInit(){
Angular-9
this.service.getData().subscribe((posRes)=>{
this.result = posRes;
},errCallBack);
};
contact.component.html
<h1>{{result | json}}</h1>
contact.module.ts
import { NgModule } from "@angular/core";
{path:"",component:ContactComponent}
];
@NgModule({
declarations:[ContactComponent],
imports:[CommonModule,
Angular-9
HttpClientModule,
TokenModule,
RouterModule.forChild(appRoutes)],
providers:[ContactService],
exports:[ContactComponent]
})
TokenModule
******************************
src
app
token
gettoken.service.ts
auth.interceptor.ts
token.module.ts
******************************
gettoken.service.ts
@Injectable({
providedIn:"root"
})
Angular-9
public getToken():string{
return obj.token;
};
};
auth.interceptor.ts
@Injectable({
providedIn:"root"
})
constructor(private service:FetchTokenService){}
intercept(req:HttpRequest<any>,handler:HttpHandler)
:Observable<HttpEvent<any>>{
if(req.url == "http://localhost:8080/login"){
return handler.handle(req);
Angular-9
}else{
setHeaders:{
token:this.service.getToken()
});
return handler.handle(req1);
};
};
token.module.ts
@NgModule({
imports:[CommonModule],
providers:[FetchTokenService,{
provide:HTTP_INTERCEPTORS,
useClass:authInterceptor,
multi:true
Angular-9
}]
})
PortfolioModule
**********************************
src
app
portfolio
services
portfolio.service.ts
components
portfolio.component.ts
portfolio.component.html
module
portfolio.module.ts
***********************************
portfolio.service.ts
import { Injectable } from "@angular/core";
return this.http.get("http://localhost:8080/portfolio");
};
};
portfolio.component.ts
@Component({
selector:"portfolio",
templateUrl:"./portfolio.component.html"
})
private result:any;
constructor(private service:PortfolioService){}
ngOnInit(){
this.service.getData().subscribe((posRes)=>{
this.result = posRes;
},errCallBack);
};
Angular-9
portfolio.component.html
<h1>{{result | json}}</h1>
portfolio.module.ts
AboutModule
**********************************
src
app
about
services
about.service.ts
components
about.component.ts
about.component.html
module
about.module.ts
***********************************
about.service.ts
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn:"root"
})
export class AboutService{
constructor(private http:HttpClient){}
public getData():Observable<any>{
return this.http.get("http://localhost:8080/about");
Angular-9
};
};
about.component.ts
@Component({
selector:"about",
templateUrl:"./about.component.html"
})
private result:any;
constructor(private service:AboutService){}
ngOnInit(){
this.service.getData().subscribe((posRes)=>{
this.result = posRes;
},errCallBack);
};
about.component.html
<h1>{{result | json}}</h1>
Angular-9
about.module.ts
{path:"",component:AboutComponent}
];
@NgModule({
declarations:[AboutComponent],
imports:[CommonModule,
HttpClientModule,
TokenModule,
RouterModule.forChild(appRoutes)],
providers:[AboutService],
exports:[AboutComponent]
})
DashboardModule
**********************************
dashboard
services
logout.service.ts
components
dashboard.component.ts
dashboard.component.html
module
dashboard.module.ts
************************************
logout.service.ts
@Injectable({
providedIn:"root"
})
constructor(private http:HttpClient){}
public logout():Observable<any>{
return this.http.get("http://localhost:8080/logout")
Angular-9
};
};
dashboard.component.ts
@Component({
selector:"dashboard",
templateUrl:"./dashboard.component.html"
})
constructor(private router:Router,
private service:logoutService){}
logout():any{
this.service.logout().subscribe((posRes)=>{
if(posRes.logout == "success"){
window.localStorage.removeItem("login_details");
this.router.navigate(["/"]);
},errCallBack);
};};
Angular-9
dashboard.component.html
<b>About</b>
</a>
<b>Portfolio</b>
</a>
<b>Contact</b>
</a>
<button (click)="logout()">Logout</button>
<br><br>
<router-outlet></router-outlet>
dashboard.module.ts
{path:"",component:dashboardComponent,
children:[{path:"about",loadChildren:"src/app/about/module/about
.module#AboutModule"},
{path:"portfolio",loadChildren:"src/app/portfolio/module/portfol
io.module#PortfolioModule"},
{path:"contact",loadChildren:"src/app/contact/module/contact.mod
ule#ContactModule"}]}
];
@NgModule({
declarations:[dashboardComponent],
imports:[CommonModule,
HttpClientModule,
TokenModule,
RouterModule.forChild(appRoutes)],
providers:[logoutService],
exports:[dashboardComponent]
})
LoginModule
***************************************
login
services
login.service.ts
components
login.component.ts
login.component.html
module
login.module.ts
***************************************
login.service.ts
@Injectable({
providedIn:"root"
})
constructor(private http:HttpClient){}
public login(data:any):Observable<any>{
Angular-9
return
this.http.post("http://localhost:8080/login",data);
};
};
login.component.ts
@Component({
selector:"login",
templateUrl:"./login.component.html"
})
constructor(private service:loginService,
private router:Router){}
public login(data:any){
this.service.login(data).subscribe((posRes)=>{
if(posRes.login == "success"){
window.localStorage.setItem("login_details",str);
this.router.navigate(["/dashboard"]);
Angular-9
}else{
alert("Login Fail");
},errCallBack);
}; };
login.component.html
<fieldset>
<legend>Login</legend>
<br><br>
<br><br>
<button (click)="login({'uname':uname,
'upwd':upwd})">Login</button>
</fieldset>
login.module.ts
{path:"",component:loginComponent}
];
@NgModule({
declarations:[loginComponent],
imports:[CommonModule,
HttpClientModule,
FormsModule,
RouterModule.forChild(appRoutes)],
providers:[loginService],
exports:[loginComponent]
})
AppModule
********************************
app.component.ts
app.component.html
app.module.ts
********************************
Angular-9
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
title = 'miniproject';
app.component.html
<router-outlet></router-outlet>
app.module.ts
{path:"",loadChildren:"./login/module/login.module#LoginModule"}
, {path:"dashboard",
loadChildren:"./dashboard/module/dashboard.module#DashboardModul
e"}
];
@NgModule({
declarations: [
AppComponent
],
Imports:[ BrowserModule,
LoginModule,
DashboardModule,
RouterModule.forRoot(appRoutes)
],
providers: [],
bootstrap: [AppComponent]
})
Terminal-1
----------
> cd miniproject
> cd server
Terminal-2
----------
> cd miniproject
> ng s -o
Result:
Angular-9
let generateToken =
require("./config/generate.Token");
app.use(cors());
Angular-9
app.use(bodyparser.json());
host: "localhost",
user: "root",
password: "admin",
database: "miniproject",
port: 3306
});
connection.connect();
//Login request
connection.query(
if (records.length > 0) {
uname: req.body.uname,
Angular-9
upwd: req.body.upwd
},
"Raju"
);
obj.token = newToken;
} else {
);
});
app.get("/about",[auth],(req,res)=>{
else{
res.send(records);
}); });
app.get("/contact",[auth],(req,res)=>{
else{
res.send(records);
});
});
app.get("/portfolio",[auth],(req,res)=>{connection.query(`select
* from portfolio`,(err,records,fields)=>{
else{
res.send(records);
});
});
//Login code
Angular-9
app.get("/",[require("../config/auth")],(req,res)=>{
require("../config/token").token = "";
res.send({logout:"success"});
}else{
res.send({logout:"fail"});
});
app.listen(8080);
1) mysql
2) mongodb
3) sql server
Queries
-------
*************************************
host : localhost
user : root
password: root
Angular-9
database: miniproject
tables : login_details
about
*************************************
Queries
> mongod
> mongo
> db.createCollection("portfolio");
> db.portfolio.insert({"sno":1,
"sub":"JavaScript",
"demand":"High"});
> db.portfolio.find();
*************************************
protocol : mongodb
port : 27017
database : miniproject
collection : portfolio
*************************************
Angular-9
*****************************
server : localhost
user : sa
password: 123
database: miniproject
table : contact
*****************************
Step 2.
Ex.
server
Step 3.
mysql
mssql
body-parser
cors
jwt-simple --save
Angular-9
server
common
imports.js
mysql_properties.js
mssql_properties.js
mysql_connection.js
generateToken.js
token.js
auth.js
login
login.js
about
about.js
portfolio
portfolio.js
contact
contact.js
logout
logout.js
server.js
**************************************************************
Angular-9
properties.
Step 5.
> mongod
Angular-9
Step 6.
=> http://localhost:8080/portfolio(GET)
imports.js
module.exports = {
express : require("express"),
mysql : require("mysql"),
mssql : require("mssql"),
mongodb : require("mongodb"),
bodyparser : require("body-parser"),
cors : require("cors"),
jwt : require("jwt-simple") };
mysql_properties.js
module.exports = {
host : "localhost",
user : "root",
password: "root",
database: "miniproject" };
Angular-9
mssql_properties.js
module.exports = {
server : "localhost",
user : "sa",
password: "123",
database: "miniproject"
};
mysql_connection.js
module.exports = {
server : "localhost",
user : "sa",
password: "123",
database: "miniproject"
};
generateToken.js
module.exports = function(obj,password){
return require("./imports").jwt.encode(obj,password);
};
token.js
module.exports = {
"token" : ""
};
Angular-9
auth.js
/*
as middleware
*/
module.exports = (req,res,next)=>{
if(req.header("token") == require("./token").token){
next();
}else{
res.send("UnAuthorized User...!");
};
login.js
module.exports = require("../common/imports").express
.Router()
.post("/",(req,res)=>{
connection.connect();
connection.query("select * from login_details where
uname='"+req.body.uname+"' and
upwd='"+req.body.upwd+"'",(err,records)=>{
if(records.length>0){
var token = require("../common/generateToken")({
'uname':req.body.uname,
'upwd':req.body.upwd
},'[email protected]');
require("../common/token").token = token;
res.send({"login":"success","token":token});
}else{
res.send({"login":"fail"})
}
});
});
about.js
module.exports = require("../common/imports").express
.Router()
.get("/",
[require("../common/auth")],
(req,res)=>{
connection.connect();
(err,records,fields)=>{
if(err)
throw err;
else
res.send(records);
});
});
portfolio.js
module.exports = require("../common/imports").express
.Router()
.get("/",[require("../common/auth")],(req,res)=>{
let nareshIT =
require("../common/imports").mongodb.MongoClient;
nareshIT.connect("mongodb://localhost:27017/miniproject",
(err,db)=>{
if(err)
throw err;
else{
db.collection("portfolio")
.find()
.toArray((err,array)=>{
if(err)
Angular-9
throw err;
else
res.send(array);
});
}
});
});
contact.js
module.exports = require("../common/imports").express
.Router()
.get("/",[require("../common/auth")],(req,res)=>{
let mssql = require("../common/imports").mssql;
mssql.connect(require("../common/mssql_properties"),(err)=>{
if(err)
throw err;
else{
let request = new mssql.Request();
request.query(`select * from
contact`,(err,records)=>{
if(err)
throw err;
else{
res.send(records);
}
mssql.close();
});
} }); });
Angular-9
logout.js
module.exports = require("../common/imports").express
.Router()
.get("/",[require("../common/auth")],(req,res)=>{
//delete the server token
require("../common/token").token = "";
res.send({"logout":"success"});
});
server.js
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended:false}));
app.use(require("./common/imports").cors());
app.use("/login",require("./login/login"));
app.use(require("./common/auth"));
app.use("/about",require("./about/about"));
app.use("/portfolio",require("./portfolio/portfolio"));
app.use("/contact",require("./contact/contact"));
app.use("/logout",require("./logout/logout"));
app.listen(8080);