Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 98

PREPARED BY GUHAN GANESAN M.E.

,
INTRODUCTION
 Angular is a TypeScript-based open-source web
application framework led by the Angular Team
at Google and by a community of individuals and
corporations.
 Angular is a complete rewrite from the same team that
built AngularJS.
 Angular 2.0+ has a feature of modularity, where a
single application is built by separating it in many
modules.
WHY IS ANGULAR JS CALLED ANGULAR?

 Because HTML has Angular brackets and "ng"


sounds like "Angular".
 Because Angular JS can be written inside the
angle brackets of HTML that is why it is known
as Angular JS .
DIFFERENCES BETWEEN ANGULAR AND
ANGULARJS
 Angular was a complete rewrite of AngularJS.
 Angular does not have a concept of “scope” or
controllers instead, it uses a hierarchy of components as
its main architectural concept.
 Angular has a simpler expression syntax, focusing on “[
]” for property binding, and “( )” for event binding
 Mobile development – Desktop development is much
easier when mobile performance issues are handled
first. Thus, Angular first handles mobile development.
 Modularity – Angular follows modularity. Similar
functionalities are kept together in same modules. This
gives Angular a lighter & faster core.
ANGULAR FEATURES
BUILDING BLOCKS OF ANGULAR

 Modules
 Components

 Templates

 Metadata

 Data binding

 Directives

 Services

 Dependency injection
NODE JS
 Node.js is a server-side platform built on Google
Chrome's JavaScript Engine (V8 Engine).
 Node.js was developed by Ryan Dahl in 2009 and
its latest version is v0.10.36.
WHY NEED NODE JS?
 A web browser such as Chrome, Firefox or
Internet Explorer understands only Javascript so
we have to transpile our Typescript to Javascript
and for that we use typescript transpiler which
requires NodeJS.
 NPM (Node Package Manager) comes
with node.js by default. NPM allows you to
manage your dependencies.
INSTALLATION
 Go to, https://nodejs.org/ and download
recommended package then install Node JS
 Go to, https://code.visualstudio.com/ and
download windows package then install
 Go to cmd in visualstudio using ( Ctrl+~)

 Check Node version in cmd using ( node -v)

 Check NPM version in cmd using ( npm -v)

 If it is not available, use ( npm install npm)

 Now, check NPM version use ( npm -v )


CONT..
 Create any folder in any directory: For Ex.
Angular in my Local disk D drive.
 Install the library files globally

-> npm install -g @angular/cli


 Create New project: ng new poroject_name

 Then select the project: cd poroject_name

 Now start your project: npm start or ng serve

 To confirm: Open your browser use this link:


http://localhost:4200
MODULE
 A module is a cohesive block of code with a
related set of capabilities which have a specific
application domain or a workflow.
 A module is a mechanism to group components,
directives, pipes and services that are related, in
such a way that can be combined with other
modules to create an application.
 Any angular module is a class with
@NgModule decorator.
DECORATORS

 Decorators are functions that modify JavaScript


classes.
 Decorators are basically used for attaching
metadata to classes so that, it knows the
configuration of those classes and how they
should work.
 NgModule is a decorator function that takes
metadata object whose properties describe the
module.
PROPERTIES OF DECORATORS
 declarations: The classes that are related to views and it
belong to this module. There are three classes of Angular
that can contain view: components, directives and pipes.
 exports: The classes that should be accessible to the
components of other modules.
 imports: Modules whose classes are needed by the
component of this module.
 providers: Services present in one of the modules which is
to be used in the other modules or components. Once a
service is included in the providers it becomes accessible in
all parts of that application
 bootstrap: The root component which is the main view of
the application. This root module only has this property and
it indicates the component that is to be bootstrapped.
MVVM
MODEL
 A Model is a container defining the structure of an
entity, following the object oriented principle. It is
defined by your content.
 So if you want to use a Model for a User, it could look
like this.
 class User {

name:string;
email:string;
address:string;
}
Note that: Models should not contain any logic. All your
logic should be defined in the ViewModel.
VIEW

 The View is the visual layer of the application,


including all visual elements shown on the user’s
screen.
 In the case of Angular 2 the view is defined in a
template.
 These templates are written in HTML and CSS
but also contain angular specific elements.
 These templates a connected to the ViewModel
via data-binding.
 Templates are always part of a component.
VIEWMODEL
 The ViewModel is an abstract part of the View,
managing the models and properties to show on
the screen.
 It contains all the logic for the page. View and
ViewModel are often connected via data binding.
 That means, that changes in the ViewModel, for
example on a property, are instantly applied to
the view, changing e.g. the text shown on the
screen.
 In angular, the ViewModel is represented by the
Typescript part of a component.
COMPONENT
 Components are the most basic building block of
an UI in an Angular application.
 An Angular application is a tree of Angular
components.
 Angular components are a subset of directives.
Unlike directives, components always have a
template and only one component can be
instantiated per an element in a template.
ADD CSS BOOTSTRAP
 npm install bootstrap@4 jquery –save
 Add url in angular.json

"styles": [ "src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.min.c
ss" ],
DATA BINDING
 Databinding is a powerful feature of Angular.
 Angular Databinding is used for communication.

 It is used to communicate between your TypeScript


code (your business logic) and the other component
(HTML layout).
 Databinding is necessary because when we write
the code in TypeScript, it is compiled to JavaScript
and the result is shown on HTML layout.
 Thus, to show the correct and spontaneous result to
the users, a proper communication is necessary.
ONE WAY DATA BINDING
In one-way databinding, the value of the Model is
used in the View (HTML page) but you can't
update Model from the View.
 Angular Interpolation / String Interpolation,
Property Binding, and Event Binding are the
example of one-way databinding.

{ { }}
TWO WAY DATA BINDING
 In two-way databinding, automatic synchronization
of data happens between the Model and the View.
 Here, change is reflected in both components.

 Whenever you make changes in the Model, it will


be reflected in the View and when you make
changes in View, it will be reflected in Model.
 This happens immediately and automatically,
ensures that the HTML template and the
TypeScript code are updated at all times.
CLASSIFICATION OF DATA BINDING
INTERPOLATION BINDING
 App.component.ts  App.component.html

export class AppComponent { <strong>{{firstname}}</strong>


firstname: string = "Sachin"; <strong>{{lastname}}</strong>
lastname:string = "Tendulkar"

}
PROPERTY BINDING
 App.component.ts  App.component.html

export class AppComponent { <span [innerHTML]='firstname'>


firstname: string = "Sachin"; </span>
lastname:string = "Tendulkar"
}
PROPERTY BINDING
 App.component.ts  App.component.html

export class AppComponent { <span [innerHTML]='firstname'>


firstname: string = "Sachin"; </span>
lastname:string = "Tendulkar"
}
ATTRIBUTE BINDING
App.component.ts

colSpanValue:number=2;

App.component.html

<table>
<tr>
<td [attr.colspan]="colSpanValue”
style="background-color: red">td1</td>
</tr>
</table>
CLASS BINDING
App.component.css
<table border="1">
<thead>

.myclass <tr>
<th [attr.colspan]="2"
{ [class.myclass]='true'>Student Details</th>
text-align: left;
</tr>
color:blue; </thead>
} <tbody>
</tbody>
</table>
STYLE BINDING
<thead>
<tr>
<th [attr.colspan]="2" [style.background-
color]="'red'“>
Student Details</th>

</tr>
</thead>
TWO WAY DATA BINDING
App.component.ts
export class AppComponent {
data1: string = '‘”;
}

App.component.html
<input [value]='data1' (input)='data1 =
$event.target.value'>

<p> {{data1}}</p>
FORMSMODULE(TWO WAY DATABINDING)
App.module.ts
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
]

App.component.html

<input [(ngModel)]="name">
<p>{{name}}</p>
EVENT BINDING
 To bind the events along with the methods. This process
is known as event binding.
 Event binding is used with parenthesis ().
App.component.ts
msg:string="Hi";
myEvent()
{
this.msg="Bye";
}
App.component.html
<button (click)="myEvent()">click</button>
<p>{{msg}}</p>
CONT..
App.component.ts
msg1:string="";
myEvent1( x: any)
{
//console.log(x);
//this.msg1+=x.target.value+"--";
//(<HTMLInputElement>event.target).value
this.msg1+=(<HTMLInputElement>x.target).value+"--";
}
App.component.html
<input (keyup)= "myEvent1($event)" >

<p>{{msg1}}</p>
TEMPLATE REFERENCE VARIABLE

 There's another way to get the user data: use


Angular template reference variable.
 These variables provide direct access to an
element from within the template.
 To declare a template reference variable, precede
an identifier with a hash (or pound) character (#).
CONT..
App.component.html
Ex1:
<input #test (keyup)="0"> <br>
<p>{{test.value}}</p>
Ex2:
App.component.html
<input #test1 (keyup.enter)="onEnter(test1.value)"> <br>
<p>{{msg3}}</p>
App.component.ts
msg3:string="";
onEnter(y:any)
{
this.msg3=y;
}
CALCULATOR DESIGNING
App.component.html

<table>
<tr><input [(ngModel)]="data"></tr>
<tr>
<button (click)=send(1)>1</button> <button (click)=send(2)>2</button>
<button (click)=send(3)>3</button> <button (click)=send(4)>4</button>
</tr>
<tr><button (click)=send(5)>5</button> <button (click)=send(6)>6</button>
<button (click)=send(7)>7</button> <button (click)=send(8)>8</button>
</tr>
<tr><button (click)=send(9)>9</button> <button (click)=send(0)>0</button>
<button (click)="send('+')">+</button> <button (click)="send('-')">-</button>
</tr>
<tr><button (click)="send('*')">*</button> <button (click)="send('/')">/</button>
<button (click)="send('=')">=</button> <button (click)="send('clr')">AC</button>
</tr>
</table>
CONT..
App.component.css
button{width:50px;}
input{width:200px;}

App.component.ts
data:any="";
result:any;
send(x:any)
{
switch(x)
{
case 1: this.data+="1"; break;
case 2: this.data+="2"; break;
case 3: this.data+="3"; break;
case 4: this.data+="4"; break;
case 5: this.data+="5"; break;
CONT..
case 6: this.data+="6"; break;
case 7: this.data+="7"; break;
case 8: this.data+="8"; break;
case 9: this.data+="9"; break;
case 0: this.data+="0"; break;

case "+": this.data+="+"; break;


case "-": this.data+="-"; break;
case "*": this.data+="*"; break;
case "/": this.data+="/"; break;

case "=":
this.result=eval(this.data);
this.data=this.result;
break;

case "clr": this.data=""; break;

}
}
DIRECTIVES

 The Angular 8 directives are used to manipulate


the DOM.
 By using Angular directives, you can change the
appearance, behavior or a layout of a DOM
element.
TYPES OF DIRECTIVES
 Component Directives
 Structural Directives

 Attribute Directives
COMPONENT DIRECTIVES
 Component directives form the main class.
 It possesses the details about how the
component should be instantiated, processed and
utilized at runtime.
STRUCTURAL DIRECTIVES
 As far as a structure directive is concerned, it is
associated with manipulating the DOM elements.
 You will find an asterisk (*) prefix before the
directive.
NGIF DIRECTIVES
App.component.html

<button (click)="myFun1()">click</button>
<p *ngIf="b1">{{msg4}}</p>

<p *ngIf="b1; else testElse">{{msg4}}</p>


<ng-template #testElse>
{{"Welcome"}}
</ng-template>

App.component.ts
B1:boolean=false;
msg4:string="";
myFun1()
{
this.b1=true;
this.msg4="Hello";
NGFOR DIRECTIVE
App.component.ts
export class AppComponent {

bks:Books[]=[
{id:1001,title:"Tamil",author:"Raja"},
{id:1002,title:"English",author:"Guhan"},
{id:1003,title:"Science",author:"Ramesh"}
]
}

class Books
{
title:string;
author:string;
id:number;
}
CONT..
App.component.html

<table border="1">
<tr><th>Id</th><th>Title</th><th>Author</th></tr>
<tr *ngFor="let data of bks">
<td>{{data.id}}</td>
<td>{{data.title}}</td>
<td>{{data.author}}</td>
</tr>
</table>
NGSWITCH DIRECTIVES
App.component.html

<select [(ngModel)]="myValue">
<option *ngFor="let list of bks" [value]="list.id">
{{list.id}}
</option>
</select>
<ul [ngSwitch]="myValue">
<li *ngSwitchCase="'1001'">{{"Chennai"}}</li>
<li *ngSwitchCase="'1002'">{{"Madurai"}}</li>
<li *ngSwitchCase="'1003'">{{"Trichy"}}</li>
</ul>
CUSTOM DIRECTIVE
 ng generate directive mydirective

 CREATE src/app/mydirective.directive.spec.ts
(244 bytes)
 CREATE src/app/mydirective.directive.ts (151
bytes)
 UPDATE src/app/app.module.ts (544 bytes)
CONT..
Mydirective.directive.ts
import { Directive, ElementRef } from '@angular/core';

@Directive({
selector: '[appMydirective]'
})
export class MydirectiveDirective {

constructor(el:ElementRef) {
el.nativeElement.style.color="blue";
}
}
App.component.html
<!– apply the attribute directive -- >
<p appMydirective> Welcome!!!</p>
HOSTLISTENER
App.component.html
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appMydirective]'
})
export class MydirectiveDirective {

constructor(private el:ElementRef) {
//el.nativeElement.style.color="blue";
}

@HostListener('mouseenter') onMouseEnter()
{
this.applyMyCss("red");
}

@HostListener('mouseleave') onMouseLeave()
{
this.applyMyCss("green");
}
applyMyCss(x:string)
{
this.el.nativeElement.style.color=x;
}
}
ROUTING
 Cmd: ng generate module app-routing --flat --module=app
 --flat puts the file in src/app instead of its own folder.
 --module=app tells the CLI to register it in the imports array of the AppModule.

By using selector
<app-home></app-home>
<app-about></app-about>
<app-profile></app-profile>

App-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
GENERATE NEW COMPONENT
 ng g c home
 ng g c about

 ng g c profile

src/app/app-routing.module.ts
 import {HomeComponent} from './home/home.component';
 import {AboutComponent} from './about/about.component';
 import {ProfileComponent} from './profile/profile.component';
ROUTES ARRAY
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import {HomeComponent} from './home/home.component';


import {AboutComponent} from './about/about.component';
import {ProfileComponent} from './profile/profile.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'profile', component: ProfileComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
CONT..
App.component.html

<router-outlet>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<a routerLink="/profile">Profile</a>
</router-outlet>
FOR CHILD ROUTING
 E:\Angular\myapp\src\app\home>ng g c create
 ng g c update

 Ng g c view

Home.component.html
<h2>Home</h2>
<router-outlet>
</router-outlet>
CONT..
app-routing.module.ts

import { CreateComponent } from './home/create/create.component';


import { UpdateComponent } from './home/update/update.component';
import { ViewComponent } from './home/view/view.component';

const routes: Routes = [


{
path: 'home', component: HomeComponent,
children:[
{path: 'create', component: CreateComponent},
{path: 'update', component: UpdateComponent},
{path: 'view', component: ViewComponent},
]
},

{ path: 'about', component: AboutComponent },


{ path: 'profile', component: ProfileComponent }
];
PIPES
The pipe takes the data as input and transforms it the desired output.
App.component.ts
mydate=new Date();
arr:any=['a','b','c','d','e','f','g','h','i'];
jsonval = {name: 'Anbu', age: '27', address:{no: '12/A', street: 'North Street'}}

App.component.html

<p>{{"uppercase pipes" | uppercase}}</p>


<p>{{"lowercase pipes" | lowercase}}</p>
<p>{{ mydate | date:'d/M/y'}}</p>
<p>{{5786.76578677876 | number:'3.5'}}</p>
<p>{{00.54565 | percent}}</p>
<p>{{arr | slice:3:7}}</p>
<p>{{jsonval | json }}</p>
CUSTOM PIPES
Create mypipe.pipe.ts in app folder(component)
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name:'sqr'
})
export class MyPipe implements PipeTransform
{
transform(x:any)
{
return x*x;
}
}
CONT..
 Import mypipe.pipe.ts in app.module.ts
 import {MyPipe} from './mypipe.pipe';

 declarations: [

MyPipe
]
App.component.html
<p> {{12 | sqr }}</p>
SERVICE
 To access methods and properties across other components in the entire project.
 Run ng g service myservice in app component

Myservice.service.ts

import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})

export class MyserviceService {

constructor() { }
}
CONT..
 import {MyserviceService} from './myservice.service'; in
App.module.ts
 Include in providers: [MyserviceService],
CONT
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
constructor() { }
std:Student[] =[
{name:"Raja",age:28,email:"raja@gmail.com"},
{name:"Anbu",age:27,email:"anbu@gmail.com"},
{name:"Ramesh",age:29,email:"ramesha@gmail.com"}
]
send()
{
console.log(this.std);
}

}
class Student
{
name:string;
age:number;
email:string;
}
CONT..
App.component.ts
import { Component } from '@angular/core';
import {MyserviceService} from './myservice.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private obj:MyserviceService)
{
}
ngOnInit()
{
this.obj.send();
}
}
OBSERVABLES
 Observables provide the support for passing the
messages between publishers(Creator of Observables)
and subscribers (User of Observables) in your
application.
 Observables are declarative that is, you define the
function for publishing values, but it is not executed
until the consumer subscribes to it.
 The observable can deliver the multiple values of any
type like literals, messages, or events, depending on
the context.
 As a publisher, you can create an Observable instance
that defines a subscriber function. This is a function
that is executed when the consumer calls the
subscribe() method.
THREE TYPES OF NOTIFICATIONS

 next: Required. The handler for each delivered


value called zero or more times after execution
starts.
 error: Optional. The handler for error
notification. An error halts execution of the
observable instance.
 complete: Optional. The handler for the
execution-complete notification. Delayed values
can continue to be delivered to the next handler
after execution is complete.
SUBSCRIBING ANGULAR OBSERVABLES

 You can subscribe the observables by calling


the subscribe() method of the instance and passing an
observer object to receive the notifications.
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
 Use the Observables constructor to create an
observable stream of any type.
const obs = new Observable();
CONT..
 Create a service and model file
ng g s student --spec=false
(student.service.ts file inside the src >> app folder)
Student.model.ts
export class Student {
id: Number;
name: String;
EnrollmentNumber: Number;
College: String;
University: String;
}
CONT..
Import model file in service file and add demo data
import { Injectable } from '@angular/core';
import { Student } from './student.model';
@Injectable({ providedIn: 'root' })
export class StudentService {
students: Student[] = [
{ id: 1, name: 'Krunal', enrollmentnumber: 110470116021,
college: 'VVP Engineering College', university: 'GTU' },
{ id: 2, name: 'Rushabh', enrollmentnumber: 110470116023,
college: 'VVP Engineering College', university: 'GTU' },
{ id: 3, name: 'Ankit', enrollmentnumber: 110470116022,
college: 'VVP Engineering College', university: 'GTU' }
];
constructor() { }
}
CONT..
 import { Observable } from 'rxjs'; in student.services.ts
 We need to create one function inside the service that
will return that data in the form of observable.
 public getStudents(): any {

const studentsObservable = new Observable(


observer => { setTimeout(
() => { observer.next(this.students); },
1000);
});
return studentsObservable;
}
DEFINE THE SUBSCRIBER
import { Component, OnInit } from '@angular/core';
import { Student } from './student.model';
import { StudentService } from './student.service';
@Component({ selector: 'app-root', templateUrl:
'./app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent implements OnInit {
students: Student[] = [];
constructor(private studentservice: StudentService) {}
ngOnInit() {
const studentsObservable = this.studentservice.getStudents();
studentsObservable.subscribe(
(studentsData: Student[]) => { this.students = studentsData; }
);
}
}
DISPLAY THE DATA
<h2>Observable</h2>
<div class="container">
<div class="row" style="margin-top: 30px">
<div class="col-md-3 col-xs-6" *ngFor="let student of students">
<div class="card">
<div class="card-body">
<h5 class="card-title">{{ student.name }}</h5>
<h6 class="card-subtitle">{{ student.EnrollmentNumber}}</h6>
<p class="card-text">{{ student.College }}</p>
<p class="card-text">{{ student.University }}</p>
<a class="btn btn-primary" href="#" >Go somewhere</a>
</div>
</div>
</div>
</div>
</div>
HTTP SERVICE

 Most front-end applications communicate with


backend services over the HTTP protocol.
 Modern browsers support two different APIs for
making HTTP requests: XMLHttpRequest interface
and the fetch() API.
 The HttpClient in @angular/common/http offers a
simplified client HTTP API for Angular applications
that rests on the XMLHttpRequest interface exposed
by browsers.
MODEL
import { HttpClientModule } from '@angular/common/http'; in
app.module.ts and add HttpClientModule in imports[]

User.model.ts
export class User
{
userId:number;
id:number;
title:string;
body:string;
}
CONT..
Basic.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import {User} from './user.model';
@Injectable({
providedIn: 'root'
})
export class BasicService {
apiUrl:any='https://jsonplaceholder.typicode.com/posts';
constructor( private http:HttpClient)
{
}
getData()
{
return this.http.get<User[]>(this.apiUrl);
}
}
CONT..
App.component.ts
import { Component } from '@angular/core';
import{BasicService} from './basic.service';
import {User} from './user.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
users:User[];
constructor(private bs:BasicService) {}

ngOnInit()
{
this.bs.getData().subscribe(data=>this.users=data);
}
}
CONT..
App.component.html

<table>
<tr>
<th>Id</th>
<th>IserId</th><th>Title</th><th>Body</th></tr>
<tr *ngFor="let item of users">
<td>{{item.id}}</td>
<td>{{item.userId}}</td>
<td>{{item.title}}</td>
<td>{{item.body}}</td>
</tr>
</table>
ANGULAR CRUD
 Create a model in app/model/employee.model.ts
export class Employee {
id?: number;
employee_name?: string;
employee_salary?: number;
employee_age?: number;
}
HTTP SERVICES
 Create app/service/employee.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Employee } from '../model/employee.model';

@Injectable({
providedIn: 'root'
})
export class EmployeeService {

constructor(private http: HttpClient) { }


baseUrl = 'http://localhost:3000/employees/';
getEmployees() {
return this.http.get<Employee[]>(this.baseUrl);
}
deleteEmployees(id: number) {
return this.http.delete<Employee[]>(this.baseUrl + id);
}
createUser(employee: Employee) {
return this.http.post(this.baseUrl, employee);
}
getEmployeeById(id: number) {
return this.http.get<Employee>(this.baseUrl + id);
}
updateEmployee(employee: Employee) {
return this.http.put(this.baseUrl + employee.id, employee);
}
}

Note:
import { HttpClientModule } from '@angular/common/http';
import { EmployeeService } from './service/employee.service';
in app.module.ts and include in providers[EmployeeService] and
Imports[HttpClientModule] as usual…
COMPONENTS

 Generate componets
 App/ ng g c add-emp
 App/ ng g c edit-emp
 App/ ng g c list-emp
 Import components in app-routing.module.ts
And write a coding for routing

export const routes: Routes = [


{ path: '', component: ListEmpComponent, pathMatch: 'full' },
{ path: 'list-emp', component: ListEmpComponent },
{ path: 'add-emp', component: AddEmpComponent },
{ path: 'update-emp', component: EditEmpComponent }
];
JSON SERVER
 https://www.npmjs.com/package/json-server
 npm install -g json-server
 Create a src/db.json file with some data
{
"employees": [
{
"id": 2,
"employee_name": "Ranjit",
"employee_salary": 154000,
"employee_age": "29"
},
]
}
//json-server --watch db.json
FORM
 Add-emp.component.html
<div class="col-md-6">
<h2 class="text-center">{{empformlabel}}</h2>
<form [formGroup]="addForm" class="form">
<div class="form-group">
<label for="empId">Employee Id:</label>
<input type="number" formControlName="id" name="empId"
class="form-control">
</div>
<div class="form-group">
<label for="empName">Employee Name:</label>
<input formControlName="employee_name"
name="empName" class="form-control">
</div>
<div class="form-group">
<label for="empSalary">Employee Salary:</label>
<input formControlName="employee_salary" name="employee_salary"
class="form-control">
</div>

<div class="form-group">
<label for="empAge">Employee Age:</label>
<input formControlName="employee_age" name="empAge" class="form-control">
</div>

<button class="btn btn-success" (click)="onSubmit()">Save</button>


<button class="btn btn-success" (click)="onUpdate()">Update</button>
<p>Form value: {{ addForm.value | json }}</p>

</form>
</div>
//add-emp.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { EmployeeService } from '../service/employee.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-add-emp',
templateUrl: './add-emp.component.html',
styleUrls: ['./add-emp.component.scss']
})
export class AddEmpComponent implements OnInit {

empformlabel = 'Add Employee';


empformbtn = 'Save';
constructor(private formBuilder: FormBuilder,
private router: Router, private empService: EmployeeService) {}
addForm: FormGroup;
btnvisibility = true;
ngOnInit() {

this.addForm = this.formBuilder.group({
id:'',
employee_name:'',
employee_salary:'',
employee_age:''
});

}
onSubmit() {
console.log('Successfully Created');
this.empService.createUser(this.addForm.value)
.subscribe(data => {
this.router.navigate(['list-emp']);
},
error => {
alert(error);
});
}
}
//List-emp.component.ts
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../service/employee.service';
import { Employee } from '../model/employee.model';
import { Router } from '@angular/router';

@Component({
selector: 'app-list-emp',
templateUrl: './list-emp.component.html',
styleUrls: ['./list-emp.component.scss']
})
export class ListEmpComponent implements OnInit {

employees: Employee[];
constructor(private empService: EmployeeService, private router: Router )
{}

ngOnInit() {
this.empService.getEmployees()
.subscribe((data: Employee[]) => {
this.employees = data;
});
}
deleteEmp(employee: Employee): void {
this.empService.deleteEmployees(employee.id)
.subscribe(data => {
this.employees = this.employees.filter(u => u !== employee);
});
}
editEmp(employee: Employee): void {
localStorage.removeItem('editEmpId');
localStorage.setItem('editEmpId', employee.id.toString());
this.router.navigate(['update-emp']);
}

addEmp(): void {
localStorage.removeItem('editEmpId');
this.router.navigate(['add-emp']);
}
}
<div class="col-md-12">
<button (click)="addEmp()" class="btn btn-info"> Add Employee</button>
<h2> User Details</h2>
<div class="table-responsive table-container">
<table class="table" >
<thead>
<tr> <th>Id</th> <th>Employee Name</th> <th>Salary</th> <th>Age</th> </tr>
</thead>
<tbody>
<tr *ngFor="let emp of employees">
<td class="hidden">{{emp.id}}</td>
<td>{{emp.employee_name}}</td>
<td>{{emp.employee_salary}}</td>
<td>{{emp.employee_age}}</td>
<td>
<button (click)="deleteEmp(emp)" class="btn btn-info"> Delete</button>
<button (click)="editEmp(emp)" style="margin-left: 20px;" class="btn btn-info">
Edit</button>
</td> </tr> </tbody>
</table>
</div>
</div>
Edit-emp.component.html

<div class="col-md-6">
<h2 class="text-center">{{empformlabel}}</h2>
<form [formGroup]="editForm" novalidate class="form">

<div class="form-group">
<label for="empId">Employee Id:</label>
<input type="number" formControlName="id" name="empId" class="form-
control">
</div>
<div class="form-group">
<label for="empName">Employee Name:</label>
<input formControlName="employee_name" name="empName" class="form-
control">
</div>
<div class="form-group">
<label for="empSalary">Employee Salary:</label>
<input formControlName="employee_salary" name="employee_salary"
class="form-control">
</div>
<div class="form-group">
<label for="empSalary">Employee Salary:</label>
<input formControlName="employee_salary" name="employee_salary"
class="form-control">
</div>
<div class="form-group">
<label for="empAge">Employee Age:</label>
<input formControlName="employee_age" placeholder="Employee Age"
name="empAge" class="form-control" id="empAge">
</div>
<button class="btn btn-success" (click)="onUpdate()">Update</button>
<p>Form value: {{ editForm.value | json }}</p>

</form>

</div>
Edit-emp.component.ts

import { Component, OnInit } from '@angular/core';


import { FormBuilder, FormGroup} from '@angular/forms';
import { EmployeeService } from '../service/employee.service';
import { Router } from '@angular/router';

@Component({
selector: 'app-edit-emp',
templateUrl: './edit-emp.component.html',
styleUrls: ['./edit-emp.component.scss']
})
export class EditEmpComponent implements OnInit {

empformlabel = 'Edit Employee';


empformbtn = 'Update';
constructor(private formBuilder: FormBuilder,
private router: Router, private empService: EmployeeService) {
}

editForm: FormGroup;
ngOnInit() {
this.editForm = this.formBuilder.group({
id: '',
employee_name: '',
employee_salary: '',
employee_age: ''
});
const empid = localStorage.getItem('editEmpId');
if (+empid > 0) {
this.empService.getEmployeeById(+empid).subscribe(data => {
this.editForm.patchValue(data);
});
}
}
onUpdate() {
console.log('Update fire');
this.empService.updateEmployee(this.editForm.value).subscribe(data => {
this.router.navigate(['list-emp']);
},
error => {alert(error);});
}
}
FORMS
 Angular provides two different approaches for managing the
user input through the forms.
1. Reactive approach
2. Template-driven approach
 Both reactive and template-driven forms share underlying
common building blocks which are the following.
1. FormControl: It tracks the value and validation status of
the individual form control.
2. FormGroup: It tracks the same values and status for the
collection of form controls.
3. FormArray:It tracks the same values and status for the
array of the form controls.
4. ControlValueAccessor: It creates the bridge between
Angular FormControl instances and native DOM elements.
REACTIVE FORM VALIDATIONS
 import { ReactiveFormsModule } from '@angular/forms';
and include it in imports[] in app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {

}
CONT..
App.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'forms';
form =new FormGroup(
{
id:new FormControl(''),
name:new FormControl('',Validators.required),
mobile:new FormControl('',Validators.required),
email:new FormControl('',[Validators.required, Validators.email]),
pass:new FormControl('',[Validators.required, Validators.minLength(6)]),
});
onSubmit(){alert(JSON.stringify(this.form.value));}
}
CONT..
App.component.html
<h3>Reactive Forms</h3>
<div class="container">
<form [formGroup]="form" (ngSubmit)="onSubmit()">

<div class="form-group">
<label for="id">Id:</label>
<input type="number" class="form-control" id="id" formControlName="id">
</div>

<div class="form-group">
<label for="name">Name:</label>
<input type="name" class="form-control" id="name" formControlName="name"
[ngClass]="{'is-invalid':form.get('name').touched && form.get('name').invalid}">
<div class="invalid-feedback">
Name is required!!!
</div>
</div>
CONT..
<div class="form-group">
<label for="mobile">Mobile Number:</label>
<input type="text" class="form-control" id="mobile" formControlName="mobile"
[ngClass]="{'is-invalid':form.get('mobile').touched && form.get('mobile').invalid}">
<div class="invalid-feedback">
Mobile number is required!!!
</div>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" formControlName="email"
[ngClass]="{'is-invalid':form.get('email').touched && form.get('email').invalid}">

<div class="invalid-
feedback" *ngIf="form.get('email').touched && form.get('email').invalid">
<div *ngIf="form.get('email').errors.required" > Email is required!!</div>
<div *ngIf="form.get('email').errors.email" > Valid Email is required!!!</div>
</div>
</div>
CONT..
<div class="form-group">
<label for="email">Password:</label>
<input type="email" class="form-control" id="pass" formControlName="pass"
[ngClass]="{'is-invalid':form.get('pass').touched && form.get('pass').invalid}">
<div class="invalid-feedback">
Password is required!!!
</div>
</div>

<div class="form-group form-check">


<label class="form-check-label">
<input class="form-check-input" type="checkbox"> Remember me
</label>
</div>

<button type="submit" class="btn btn-


primary" [disabled]="!form.valid">Submit</button>
</form>
</div>
THANK YOU

You might also like