Professional Documents
Culture Documents
Angular 8
Angular 8
,
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?
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+~)
name:string;
email:string;
address:string;
}
Note that: Models should not contain any logic. All your
logic should be defined in the ViewModel.
VIEW
"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.
{ { }}
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.
}
PROPERTY BINDING
App.component.ts App.component.html
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
<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.result=eval(this.data);
this.data=this.result;
break;
}
}
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>
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';
<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
App.component.html
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
@Injectable({
providedIn: 'root'
})
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
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 {
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
<div class="form-group">
<label for="empAge">Employee Age:</label>
<input formControlName="employee_age" name="empAge" class="form-control">
</div>
</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 {
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
@Component({
selector: 'app-edit-emp',
templateUrl: './edit-emp.component.html',
styleUrls: ['./edit-emp.component.scss']
})
export class EditEmpComponent implements OnInit {
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>