Angular2:
Its a Javascript Framework for develop single page web application or Mobile app or Desktop app.Dev and maintains by Google.
It supports modern Browsers and older Browsers.
The size of angulrjs is larger than angular 2
Angular code write in Javascript, Typesricpt,Dart.
TS is preferred for angular.
Its a Component based FW.
AOT(Ahead Of Time) compilition imporves render speed.
Features of Angular:
Modules,Component,metadata,Templates,Dependency Injection,Directives,Data binding, Services,
**************************************************************
Type Script:
Its client side scripting progrming language, free and developed by Microsoft.
Its provides client side OOP concept, having class, interfaces, inheritance, code reusability , properites and etc.
Javascript has some loopholes means loosly typed language.But TS storngly typed,intellisence and pure Object oriented language.
Even if we write entire code in TS formate that is converts into pure Javascript code internally.
Data Types in TS:
number, string, boolean, void, any, array, Enum
Nodejs:
Its a event based asynchronous I/O Framework
Its used for developing applications.
Its provided common Javascript standards and provides libraries & software packages via npm.
Angular CLI:
Its a tool, that is used for creating project,developing and deployment.
npm install -g @angular/cli
**************************************************************
Module:
Angular is modular based application.Everything is in these modules only like Components,Services,Predefined Modules and other code files.
Every angular app has atleast one module i.e root module (AppModule).
Modules are used to separate our functionality code into parts. To avoid entire code into one place we can use more modules.
If any class is decorated with @NgModule function then it is called Module.This NgModule class is imported from angular/core namespace.
@NgModule() function having single metadata object with some properties.
Properties of @NgModule:
declarations: For declare Component,Directives,Pipes,etc
imports: For using other existing modules(predefined or userdefined)
export: For exporting Components,directives,pipes to other modules
providers: For declaring services and using into entire application.
bootstratp: For startup component ie that component is executes first.
**************************************************************
Component:
=> If any class decorating with @Component then it is called Angular Component.
=> This @Component decorator provieded by Angular ( import {Component} from "@angular/core")
=> Component is a class with Decorator, class contains properties and methods.
=> Properties are used for data and methods for logic.
=> Its has constructor() method, used for DI
=> Its has ngOnint() method, used for initialize variables,objects,arrays etc.
=> Decorator is having meta data for the class5` selector,template(Inline template)/templateUrl(External template),Provider etc.
syn: @Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [ HeroService ]
})
export class AppComponent
{
constructor(){}
ngOnInit(){}
name:string="HELLO";
}
***************************************************************************
Meta Data:
To pass/attach properties to class.Those are Modules,Components
Diff Constructor(),NgOnInit():
Constructor is runs when component is executes,used for DI,its a typescript feature.It is called before NgOnInit() method.
***************************************************************************
HTML Attribute vs DOM Property:
DOM: Document Object Model, when a Browser loads a web page,the Browser creates as a DOM of the page.
DOM contains Html elements as Objects, these objects having methods,events,properties for accessing,modifying,adding ,deleting HTML DOM elements.
<input type="button" value="clicke" disabled="true"/> this is converted as button object. Here type,value,disabled are Html attributes.
vs:
=> Attributes are defined hy HTML, where as properties are defined by the DOM.
=> Attributes initialize DOM properties.Once the initialize complete the attributes job is done.
=> Properties values can change, where attributes values can't.
=> Html attributes and DOM properties are different things.
=> Angular binding works with Properties and Events, not HTML attributes.
*************************************************************************
Life Cycle Of Angualr Component:
Every component has a life cycle, that can be managed by angular.
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngOnDestroy()
----------------------------------------
ngOnChanges():
It is executs every time when the value of input property changes, at that time it hook method receives a SimpleChanges object this containing current and previous values.
This is after constructor and before ngOnInit() method.
ngOnInit():
It is executes after constructor and ngOnChanges() hook. This is used for component initializing and receiving the data from database.
**************************************************************************
for loop in angualr:
a=[1,2,3,4];
for (let i in this.a)
{
console.log(this.a[i]);
}
---------------
a.sort();
**************************************************************************
One way Bindings:
The below are the one way bindings, means binding form a Component properties to DOM properties.
1.Interpolation {{ }}
2.Property Binding [ ]
3.Attribute Binding [attr.colspan]
4.Class Binding [class.myvar1] or [ngClass]="var1"
5.Style Binding [attr.mystyle1] or [ngStyle]="var1"
------------------------------------------------------
Interpolation: Binding from component property to Html template.Better to use when string valude bind with DOM elements
{{}}
*************************************************************************
Property Binding:[]
Non-string values can be bind with in this.
<input type="button" value="clicke" [disabled]='a'/>
a:boolean=true;
************************************************************************
Attribute Binding:
=> Interpoloation and Property Binding deals with binding component properties to DOM elements properties
=> But,not all HTML attributes having properties,methods,events
eg: colspan Html element attribute not having property in DOM.
=> In this situation, angular uses Attribute Binding.
syn: <th colspan="2"> normal attribute
<th attr.colspan="{{a}}"> a:number=2
<th [attr.colspan]="a">
*************************************************************************
Class Binding:
component:
export class AppComponent implements OnInit {
constructor() { }
classToApply:string='italicClass';
classToApply2:boolean=true;
a:boolean=true;
b:boolean=true;
addClasses(){
return {
boldClass:this.a,
italicClass:this.b
}
}
ngOnInit() { }
}
------------------------------
styles.css:
.colorClass{
color:blueviolet;
}
.boldClass{
font-weight:bold;
}
.italicClass{
font-style: italic
}
--------------------------------
component.html:
<h2 class="colorClass" [class]='classToApply'>Hello Ranjitth</h2> ----> here class="colorClass" attribute is replaced with [class]='italicClass'
<h2 class="colorClass" [class.italicClass]='classToApply2'>Hello Ranjitth</h2> ----> here class="colorClass" attribute is not replaced with [class]='italicClass'
both are available.
Note: The above is we can add single class at a time.To add multiple classess we need to use [ngClass]
<h2 class="colorClass" [ngClass]='addClassess()'> Hello Ranjitth</h2> ----> here we can observed totally 3 classes were added.
*************************************************************************
Style Binding:
The binding component class properties to DOM elements properties.
eg: <h2 style="color:red;"[style.font-style]="clr2?clr:'normal'">RANJITTH</h2>
Copmponet: clr2:boolean=true;
clr:string='italic';
=> We can add multiple style properties like below
eg:
-> Component:
export class AppComponent implements OnInit {
a:string='blue';
clr2:boolean=true;
clr:string='italic';
m1()
{
return {
'color':this.a,
'font-style':this.clr,
'font-size.px':50
}
}
}
----------------------------------------
-> Component.html:
<h2 [ngStyle]="m1();">WELCOME TO ANGULAR 2</h2>
o/p: <h2 ng-reflect-ng-style="[object Object]" style="color: blue; font-style: italic; font-size: 50px;">WELCOME TO ANGULAR 2</h2>
*************************************************************************
Event Binding:
Event binding flows data in the opposite direction i.e from an HTML elements to component.Here binding specified with paranthesis i.e ().
eg:
component.html
<button (click)='m2();'>
{{a?'Hide':'Show'}} Details
</button>
<br>
<table border="1">
<tr>
<td>First Name</td> <td>RANJITTH</td>
</tr>
<tr>
<td>Last Name</td> <td>Kumar</td>
</tr>
<tr *ngIf='a'>
<td>Gender</td> <td>Male</td>
</tr>
<tr *ngIf='a'>
<td>Email</td><td>ranjithkmr106@gmail.com</td>
</tr>
</table>
----------------------------------------
component:
export class AppComponent implements OnInit {
a:boolean=true;
m2():void{
this.a=!this.a;
}
ngOnInit() { }
}
*************************************************************************
Two Way Data Binding:
Two way data binding is a combination of Property binding and Event binding.
Binding from component to Html template and HTML elements to Componet.
syn: [(ngModel)]='name'
eg: <input type="text" [(ngModel)]='name' /> <br>
{{name}}
component: name:string="RANJITTH";
*************************************************************************
https://www.youtube.com/watch?v=nRUwdZnP-9w&list=PL5gNKLQOAmiH7d5jUr1_lpBL6e3wjPrHL&index=18
https://www.youtube.com/watch?v=5QXWy_Nai08
-------------------
Input Properties:
If we decorate with @Input() attribute to any property/variable then it is called as Input Properties.
To pass data from one component to another component (container/parent component to Nested/child component) through selector of child component and property binding.
eg:
module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from './app.component';
import { EmployeeListComponent } from "./employeeList";
import { EmployeeCountComponent } from "./employeeCount";
@NgModule({
imports: [BrowserModule,FormsModule],
exports: [],
declarations: [AppComponent,EmployeeListComponent,EmployeeCountComponent],
providers: [],
bootstrap:[EmployeeListComponent]
})
export class AppModule { }
--------------------------------
employeeList.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: 'employeeList.html'
})
export class EmployeeListComponent implements OnInit {
employeeList:any[];
x:number;
y:number;
z:number;
constructor() { }
ngOnInit() {
this.employeeList=[
{Eid:101,Ename:"RANJITTH",Salary:40000,Gender:"male"},
{Eid:102,Ename:"ELIA B",Salary:55000,Gender:"male"},
{Eid:103,Ename:"Trinadh",Salary:35000,Gender:"male"},
{Eid:104,Ename:"Pravalika",Salary:50000,Gender:"female"},
{Eid:105,Ename:"Rani",Salary:49999,Gender:"female"}
];
this.x= this.allEmps();
this.y=this.maleEmps();
this.z=this.femaleEmps();
}
allEmps():number{
return this.employeeList.length;
}
maleEmps():number{
return this.employeeList.filter(i=>i.Gender==="male").length;
}
femaleEmps():number{
return this.employeeList.filter(i=>i.Gender==="female").length;
}
}
----------------------------------------------------------
employeeList.html: this is parent html
<employee-count [a]="allEmps()"
[b]="maleEmps()"
[c]="femaleEmps()">
</employee-count> <br>
<table border="1">
<tr>
<td>EmpId</td> <td>Emp Name</td> <td>Salary</td> <td>Gender</td>
</tr>
<tr *ngFor="let i of employeeList">
<td>{{i.Eid}}</td>
<td>{{i.Ename}}</td>
<td>{{i.Salary}}</td>
<td>{{i.Gender}}</td>
</tr>
</table>
<br> <br>
{{x}} <br>
{{y}} <br>
{{z}} <br>
-------------------------------------
employeeCount.ts:
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'employee-count',
templateUrl: 'employeeCount.html'
})
export class EmployeeCountComponent implements OnInit {
// These are input properties
@Input()
a:number;
@Input()
b:number;
@Input()
c:number;
constructor() { }
ngOnInit() { }
}
------------------------------------------------
employeeCount.html:
Show: <input type="radio" name="rb" [(ngModel)]="a"/> <span>{{"All ("+a+")"}}</span>
<input type="radio" name="rb" [(ngModel)]="b"/> <span>{{"Male ("+b+")"}}</span>
<input type="radio" name="rb" [(ngModel)]="c" /> <span>{{"Female ("+c+")"}}</span>
---------------------------------------------------
*****************************************************************************************************
Output Properties:
This is also same as Input Properties, but in this passing the data from Child component to Parent component.so we need to use EventEmitter predefined class.
That EventEmitter class object should be decorate with @Output method.
syn: @Output() public childEventt = new EventEmitter();
ngOnInt(){
childEventt.emit("Hey iam from child component using EventEmitter class")
}
EventEmitter has one method i.e emit(). This method is used to emits or sends data to parent.
To capture that EventEmitter object in parent component, we need to use selector directive of the child component.
eg: <test-root (childEventt)="messagee=$event"> </test-root>
Here $event predefined variable is refers to the childs data i.e (Hey iam from child component using EventEmitter class)
Now message variable having the data.so we can use in our parent component html.
*****************************************************************************************************
Interface:
Optional property:
syn: export interface IEmployee{
Eid:number;
Ename:string;
Salary:number;
Email?:string; // optional property/variable, means its not mandatory to implement in another class.
}
export class Employee implements IEmployee{
Eid:number;
Ename:string;
Salary:number;
}
Note: Interface is used for angular only, after transpiles typescript to javascript there is no javascript code for Interface.
*************************************************************************************************
Angular Dependancy Injection:
Without create instance/object of the dependency class/service by ourself.
Angular injector can create instance/object for that dependency class/service.
If we create variable to that dependency service in constructor of our component/class then it is called DI.
syn: contructor (private processor:Processor){
}
What is use of DI:
=> whenever dependency class/service is changed their contructor, wherever using that dependency service in other classes compile errors occurs.To avoid this we need to use DI.
eg1:with out DI
export class Processor{
constructor(){
}
}
use the above class in this class
export class Computer{
private proc:Processor;
constructor(){
proc=new Processor();
}
}
Note: If we change constructor from zero argument constructor to parameterized constructer, we need to change in our class otherwise errors occured.
eg2: with DI
export class Processor{
constructor(a:number){
}
}
use the above class in this class
export class Computer{
private proc:Processor;
constructor(processor:Processor){ // DI here Angular injector is creating instance of Processor class with arguments.
this.proc=processor;
}
}
=>Easy to share data or functionality for all components i.e singleton instance/object of the service/same object can be used for all components when we register in module level.
Means if one dependencyservice1 using in component1 angular injector create single instance of the dependency.
lly, another component2 is wants to using dependencyservice1 then angular injector checks whether instance is created or not, if having created instance that will be using in component2. This concept is called singleton instance.
Single instance can be used in multiple components.
=>Easy to write and maintain Unit tests while using DI.
***********************************************************************************************
cannot find module:
While compiling with ng serve command we may missing some predefined modules like cannot find module '@angular-devkit/core'
ans: npm i --save -dev @angular/devkit/core.
************************************************************************************************
Services:
1.Creation service
2.Registering the service
3.Accessing/Utilizing service
1)If any class is decorating with @Injectable() function/decorater then it is called service.This Injectable is import from angular/core.
A set of business logic or data can be reused in multiple components.
2)we need to register in provider property of module level or component.
3)To use that service we have to go with DI in our component constructor.These Services returns the data in form of promises or Observables
Promises: These are called once & returns one single value at a time and aslo not cancellable
Observables: A sequence of items that arrives asynchronously over time.when we request to server that server will give response in observable format. Thse can handle multiple values over time
Recieve the obervable and cast into the Employee array.
Subscribe to the observable from EmpList and EmpDetails.
Assign the Emp array into the local varible.
eg1: import {Injectable} from '@angular/core'
@Injectable()
export class MyService{
SayHello():string{
return "Hello Iam Service ";
}
}
eg2: import {Component} from '@angular/core'
import {MyService} from './Myservice.service'
@component({})
export class AppComponent{
a:string;
constructor(private mySer:MyService){
this.a=mySer.SayHello();
}
}
Note: contrucotr is used for creating DI, ngOnInit is used for call remote services for time consuming.
note: https://www.youtube.com/watch?v=Ous6v0r7kXc
***********************************************************************************************
Routing:
Navigate from one component to another through UrlRouting.
1.Create Components
2.Related links:
[routerLink]
<router-outlet> </router-outlet>
3. export const routes:Routes=[
{path:'',componet:HomeComponent},
{path:'about',componet:AboutUsComponent},
{path:'contact',componet:ContactUsComponent},
{path:'**',component:ErrorComponent}
]
4.RouterModule.forRoot(routes)
Eg:
<a [routerLink]="['/']" >Home</a>
<a [routerLink]="['/about']" >AbooutUs</a>
<br/>
<router-outlet> </router-outlet> // for rendering our page in this selector
export const routes:Routes=[
{path:'',componet:HomeComponent},
{path:'about',componet:AboutUsComponent},
{path:'contact',componet:ContactUsComponent},
{path:'**',component:ErrorComponent}
]
RouterModule.forRoot(routes)
ParamsRouting:
Navigate from one component view to another through UrlRouting with parameter values.
eg:
http://localhost:4200/project/2
ActivatedRoute service to retrieve param value from url.
Constructor(private ar:ActivatedRoute){}
let empid= this.ar.snapshot.params['id'];
eg:
Module:
export const routes:Routes=[
{path:'',component:AppComponent},
{path:'about',component:AboutComponent},
{path:'project/:id',component:ProjectComponent},
{path:'contact',component:ContactComponent,children:[
{path:'employee',component:EmployeeComponent},
{path:'student',component:StudentComponent}
]}
];
--------------------------
html:
<a [routerLink]="['/']">Home</a>
<a [routerLink]="['/about']">AboutUs</a>
<a [routerLink]="['/contact']">ContactUs</a>
<a [routerLink]="['/project',2]">Project</a>
<router-outlet></router-outlet>
------------------------------
component.ts:
export class AppComponent implements OnInit {
constructor(private activatedRoute:ActivatedRoute) {
}
ngOnInit() {
let id= this.activatedRoute.snapshot.params['id'];
}
------------------------------------------------------------
project.component.ts:
export class ProjectComponent implements OnInit {
constructor(private ar:ActivatedRoute) { }
id:number;
ngOnInit() {
this.id= this.ar.snapshot.params['id']
}
**********************************************************************************
Angular Service calling webapi:
=> Module:
import { RouterModule,Routes } from "@angular/router";
import { HttpModule } from "@angular/http";
import { EmployeeService } from './employee.service';
export const routes:Routes=[
{path:"edit/:id",component:EditComponent},
{path:"delete/:id",component:DeleteComponent}
];
@NgModule(
{
declarations: [
AppComponent,
EditComponent,
DeleteComponent,
SingleComponent
],
imports: [BrowserModule,FormsModule, HttpModule,RouterModule.forRoot(routes)],
providers: [EmployeeService
],
// provide our service in provider property:
bootstrap: [AppComponent]
})
export class AppModule { }
-------------------------------------
=> Create Service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { IEmployee } from './IEmployee';
@Injectable()
export class EmployeeService {
constructor(private http: Http) { }
employees:IEmployee[];
getEmployees():Observable<IEmployee[]>
{
return this.http.get("http://localhost:49852/api/employee")
.map((resp:Response)=>resp.json());
}
getEmployee(id:number):Observable<IEmployee>
{
return this.http.get("http://localhost:49852/api/employee/"+id)
.map((resp:Response)=>resp.json())
.catch(this.errorFun);
}
editEmployee(emp:IEmployee):Observable<string>
{
return this.http.put("http://localhost:49852/api/employee",emp)
.map((resp:Response)=>resp.json())
.catch(this.errorFun);
}
insertEmployee(emp:IEmployee):Observable<string>
{
return this.http.post("http://localhost:49852/api/employee",emp)
.map((resp:Response)=>resp.json())
.catch(this.errorFun);
}
deleteEmployee(id:number):Observable<string>
{
return this.http.delete("http://localhost:49852/api/employee",id)
.map((resp:Response)=>resp.json())
.catch(this.errorFun);
}
errorFun(error:HttpErrorResponse)
{
return observable.throw(error.message || "server errror");
}
}
-----------------------------------------
=> Using this Service in our components:
import { EmployeeService } from './employee.service';
import { IEmployee } from "./IEmployee";
export class AppComponent implements OnInit {
title = 'app';
constructor(private empService:EmployeeService){
}
empls:IEmployee[];
errMsg:string;
ngOnInit()
{
this.empService.getEmployees().subscribe(resp=>this.empls=resp, error=>this.errMsg=error);
}
}
------------------------------------------
=> Displaying in Html:
<table border="1">
<tr>
<td>Eid</td><td>Ename</td><td>Salry</td><td>Manager</td> <td>Actions</td>
</tr>
<tr *ngFor="let i of empls">
<td>{{i.Eid}}</td>
<td>{{i.Ename}}</td>
<td>{{i.Sal}}</td>
<td>{{i.Manager}}</td>
<td>
<a [routerLink]="['/edit',i.Eid]">Edit</a>
<a [routerLink]="['/delete',i.Eid]">Delete</a>
</td>
</tr>
</table>
<br> <br>
<router-outlet></router-outlet>
----------------------------------------------------
For Edit:
edit.component.ts:
import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { IEmployee } from '../IEmployee';
import { ActivatedRoute } from "@angular/router";
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit
{
constructor(private empservice:EmployeeService, private act:ActivatedRoute) { }
emp:IEmployee;
editResult:string;
errMsg:string;
id:number;
ngOnInit() {
this.id=this.act.snapshot.params["id"];
this.empservice.getEmployee(this.id).subscribe(resp=>this.emp=resp, err=>this.errMsg);
}
save(){
this.emp=this.emp;
console.log(this.emp);
this.empservice.editEmployee(this.emp).subscribe(resp=>this.editResult=resp, err=>this.errMsg);
}
}
edit.html:
<table border="1">
<tr>
<td>Eid</td> <td> <input type="text" id="eid" [(ngModel)]="emp.Eid" value="{{emp.Eid}}"/> </td>
</tr>
<tr>
<td>Ename</td> <td><input type="text" id="ename" [(ngModel)]="emp.Ename" value="{{emp.Ename}}"/></td>
</tr>
<tr>
<td>Salary</td><td><input type="text" id="sal" [(ngModel)]="emp.Sal" value="{{emp.Sal}}"/></td>
</tr>
<tr>
<td>Manager</td><td><input type="text" id="mgr" [(ngModel)]="emp.Manager" value="{{emp.Manager}}"/></td>
</tr>
</table>
<br> <br>
<button type="submit" (click)="save()">Update</button>
<span *ngIf="editResult">
{{editResult}}
</span>
-----------------------------------------------------------------------------------------------------
**********************************************************************************
Routing Guard:
If we dont want to give any access pages /urls(pages components) to any users or unauthenticated users then this concept is called Routing Guard.
To restrict the users to access the rosources.
These are 4 :
canActivate,canActivateChild,canDeactivate,canLoad are Interfaces under namespace (import {canActivate,canActivateChild} from "@angular/router").
we need to implement these interfaces into our classes.
eg:
*************************************************************************************
Pipes:
To format data over template(HTML Content).we have some Built-In pipes:
uppercase
lowercase
date
currency
number
slice
json
syn: {{data/prop|pipename}}
{{data/prop|pipename:param1:param2}}
eg: {{name|uppercase}} o/p:RANJITTH
{{naem|lowercase}} o/p:ranjitth
{{tdate|date}} o/p: Jan 17,2018
{{tdate|date:'dd/MM/yyy'}}' o/p: 17/01/2018
{{mynumber|number}} o/p:45.3212344
minDigit.minFractionDigit-maxFractionDigit
{{mynumber|number:'2.2-3'}} o/p:45.321
{{myCurrency|currency}} o/p:doller45.87
{{myCurrency|currency:'INR'}} o/p:hindirupee45.87
{{myCurrency|currency:'INR':false:'2.2-3'}} o/p:INR45.870
{{name|slice:0:4}} o/p:ranj
*************************************************************************************
Custom Pipes:
we can create our own pipes depending on our requirements.
If any class is decorating with @Pipe its called as Custom pipe.
Here we need to implement transform method of PipeTransform interface in our class.
Eg:
genderPipe.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name:'mypipe'
})
export class GenderPipe implements PipeTransform{
transform(val:string):string{
debugger;
if(val=='1')
return 'Male';
else
return 'Female';
}
}
--------------------------
html:
<table border="1">
<tr>
<td>EId</td> <td>EName</td><td>EGender</td><td>ESalary</td>
</tr>
<tr *ngFor='let i of emp'>
<td>{{i.Eid}}</td>
<td>{{i.Ename}}</td>
<td>{{i.Egender|mypipe}}</td>
<td>{{i.ESalary}}</td>
</tr>
</table>
------------------------
module.ts:
we need to register our custom pipe in declarations property.
declarations: [EmployeeComponent,GenderPipe]
********************************************************************************************
Custom Pipes for Searching:
eg: search.pipe.ts
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name:'searchemp'
})
export class SearchPipe implements PipeTransform{
transform(Employees:any,txtEmpName:any):any{
//debugger;
if(txtEmpName===undefined)
{
return Employees;
}
else{
return Employees.filter(
function(x){
return x.Ename.toLowerCase().includes(txtEmpName.toLowerCase());
}
)
}
}
}
------------------------------------------------------
For sorting:
http://4dev.tech/2016/09/angular2-how-to-sort-a-json-dataset-by-field/
--------------------------------------------------
html:
<input type="text" id="txtEmpName" [(ngModel)]="findEmpName"/>
<br>
<table border="1">
<tr>
<td>Eid</td> <td>EName</td> <td>ESalary</td><td>EProject</td>
</tr>
<tr *ngFor="let i of employees | searchemp:findEmpName">
<td>{{i.Eid}}</td>
<td>{{i.Ename}}</td>
<td>{{i.Esalary}}</td>
<td>{{i.Eproject}}</td>
</tr>
</table>
--------------------------------------------------
component:
export class AboutComponent implements OnInit {
employees=[
{Eid:1,Ename:'Elia',Esalary:45000,Eproject:'java'},
{Eid:2,Ename:'Ranjitth',Esalary:35000,Eproject:'dot.net'},
{Eid:3,Ename:'Trinadh',Esalary:65000,Eproject:'rpa'},
{Eid:4,Ename:'Siva',Esalary:25000,Eproject:'Sharepoint'},
{Eid:5,Ename:'Murty',Esalary:45000,Eproject:'php'},
];
findEmpName:any;
ngOnInit() {
}
}
-------------------------------------------------------------
Module: In module we need to register in declarations property.
****************************************************************
trackBy:
This is using in ngFor directive. It will track all records. without reloading same records in DOM.
syn : <tr *ngFor="let i of employees; trackBy:getEmployeesTrackBy; let ind=index; let isEvn=even; let isOdd=odd; let isFirst=first; let isLast=last;">
getEmployeesTrackBy(index:number,i:any):any{
return i.Eid;
} // componet.ts
eg:
component.ts
export class AboutComponent implements OnInit {
employees:any[];
constructor(){
this.employees=[
{Eid:1,Ename:'Elia',Esalary:45000,Eproject:'java'},
{Eid:2,Ename:'Ranjitth',Esalary:35000,Eproject:'dot.net'},
{Eid:3,Ename:'Trinadh',Esalary:65000,Eproject:'rpa'},
{Eid:4,Ename:'Siva',Esalary:25000,Eproject:'Sharepoint'},
{Eid:5,Ename:'Murty',Esalary:45000,Eproject:'php'}
];
}
getEmployees():void{
this.employees=[
{Eid:1,Ename:'Elia',Esalary:45000,Eproject:'java'},
{Eid:2,Ename:'Ranjitth',Esalary:35000,Eproject:'dot.net'},
{Eid:3,Ename:'Trinadh',Esalary:65000,Eproject:'rpa'},
{Eid:4,Ename:'Siva',Esalary:25000,Eproject:'Sharepoint'},
{Eid:5,Ename:'Murty',Esalary:45000,Eproject:'php'},
{Eid:6,Ename:'Pvd',Esalary:65000,Eproject:'Webdesigner'}
];
}
---------------------------------------------------
html:
<table border="1">
<tr>
<td>Eid</td> <td>EName</td> <td>ESalary</td><td>EProject</td>
<td>Indexvalue</td> <td>IsEven</td> <td>IsOdd</td> <td>IsFist</td><td>IsLast</td>
</tr>
<tr *ngFor="let i of employees; trackBy:getEmployeesTrackBy; let ind=index; let isEvn=even; let isOdd=odd; let isFirst=first; let isLast=last;">
<td>{{i.Eid}}</td>
<td>{{i.Ename}}</td>
<td>{{i.Esalary}}</td>
<td>{{i.Eproject}}</td>
<td>{{ind}}</td>
<td>{{isEvn}}</td>
<td>{{isOdd}}</td>
<td>{{isFirst}}</td>
<td>{{isLast}}</td>
</tr>
</table>
<br>
<button (click)="getEmployees()" >Refresh</button>
************************************************************************
Template Driven Form:
--------------------
=>ngForm: Its a directive it is used to acccess entire form. It is assigned to local variable.
eg: <form #frmStudent="ngForm" (submit)='f1(frmStudent.value)'> </form>
=>ngModel:Its also predefiene directive, it is used to access individual form control (UI visit). In ngModel having the status that status is assigned to local variable(#stuname)
eg: <input type="text" name="sname" ngModel #stuname="ngModel" required minlength="5"/> here #stuname is local variable.
submit: its a event.
Example:
=> Module.ts:
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
@NgModule({
imports: [BrowserModule,FormsModule],
exports: [],
declarations: [AppComponent],
providers: [],
bootstrap:[AppComponent]
})
export class AppModule { }
------------------------------
=> Component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
// sname:string;
// spwd:string;
// gender:string;
// accept:boolean;
constructor() { }
ngOnInit() { }
f1(frmStudent:any)
{
console.log(frmStudent.sname);
}
}
--------------------------------------
=> app.Componet.html
<form #frmStudent="ngForm" (submit)='f1(frmStudent.value)'>
<label>StudentName</label>
<input type="text" name="sname" ngModel #stuname="ngModel" required minlength="5"/>
<span *ngIf='stuname.touched&&stuname.errors'>
<span *ngIf='stuname.errors.required' style="color:red;">
Plz enter student name---{{stuname.errors.minlength}}
</span>
<span *ngIf='stuname.errors.minlength'>
Student name should be 5 letters..
</span>
</span>
<br>
<label>password</label>
<input type="password" name="spwd" #stupwd="ngModel" ngModel required pattern="[A-Za-z0-9]{5,10}"/>
<span *ngIf='stupwd.touched&&stupwd.errors'>
<span *ngIf='stupwd.errors.required' style="color:red;">
Plz enter pwd ....
</span>
<span *ngIf='stupwd.errors.pattern' style="color:red;">
plz enter proper pwd
</span>
</span>
<br>
<label>Gender</label>
<input type="radio" name="gender" ngModel #stugender='ngModel' required value="male"/>
<input type="radio" name="gender" ngModel #stugender='ngModel' value="female"/>
<span *ngIf='stugender.touched&&stugender.errors'>
<span *ngIf='stugender.errors.required' style="color:red;">
Please select gender=={{stugender.errors.required}}
</span>
</span>
<br>
<label>Accept</label> ;
<input type="checkbox" name="accept" ngModel required #stuaccept='ngModel'/>
<span *ngIf='stuaccept.touched&&stuaccept.errors'>
<span *ngIf='stuaccept.errors.required'>
Plz check accept rules
</span>
</span>
<br>
{{frmStudent.valid}}
<br>
<input type="submit" value="Submitt" [disabled]='!frmStudent.valid'/>
</form>
--------------------------------------------------------------------------
touched : The field has been touched
untouched : The field has not been touched yet
dirty : The field has been modified
pristine : The field has not been modified yet
valid : The field content is valid
invalid : The field content is not valid
-------------------------------------
Rough:
touched : {{Eid.touched}} <br>
errors : {{Eid.errors}} <br>
dirty : {{Eid.dirty}} <br>
valid : {{Eid.valid}} <br>
invalid : {{Eid.invalid}} <br>
pristine: {{Eid.pristine}} <br>
Eid.touched&&Eid.errors : {{Eid.touched&&Eid.errors}} <br>
Eid.touched&&Eid.untouched : {{Eid.touched||true}} <br>
Eid.touched&&Eid.valid : {{Eid.touched&&Eid.valid}} <br>
o/ps of above:
touched : false
errors : [object Object]
dirty : false
valid : false
invalid : true
pristine: true
Eid.touched&&Eid.errors : false
Eid.touched&&Eid.untouched : true
Eid.touched&&Eid.valid : false
*******************************************************************************
Reactive Forms(Model Driven Form):
We need to import ReativeFormsModule
FormGroup: It is used in form tag to maintan the container for group of the controls(textboxs,radios,checkboxs etc).
eg: userForm= new FormGroup({
name: new FormControl("it is displaying in html control",[validators.required,validators.minlength(4),validators.maxlength(6)])
});
FormControl: It is used in individual controls .
Example:
import { Component, OnInit, style } from '@angular/core';
import { FormGroup,FormControl, Validators } from "@angular/forms";
@Component({
selector: 'mm',
templateUrl: 'app.component.html'
// styles: [`
// input.ng-invalid{border-left:5px solid red;}
// input.ng-valid{border-left:5px solid green;}
// `]
})
export class AppComponent implements OnInit {
constructor() { }
ngOnInit() { }
userForm=new FormGroup({
name: new FormControl("name",[Validators.required, Validators.minLength(4),Validators.maxLength(6)]),
email: new FormControl("email",[Validators.required, Validators.minLength(4),Validators.maxLength(6)]),
address: new FormGroup({
street: new FormControl("street"),
city: new FormControl("cityy"),
postalCode:new FormControl("pinco",[Validators.required,Validators.minLength(4),Validators.maxLength(6)])
})
});
f1()
{
//alert("hello"+this.userForm.value);
console.log(this.userForm.value);
}
}
----------------------------------------------------
app.component.html:
<form [formGroup]="userForm" (ngSubmit)="f1 ();">
<!-- Name: <input type="text" formControlName="name" #refName /> {{refName.className}} <br> -->
Name: <input type="text" formControlName="name" /> <br>
<div *ngIf="userForm.controls['name'].hasError('required')" style="color:red;">
please enter name
</div>
<div *ngIf="userForm.controls['name'].hasError('minlength')" style="color:orange;">
please enter min 4 letters
</div>
<div *ngIf="userForm.controls['name'].hasError('maxlength')" style="color:navy;">
Exceeded morethan 6 letters
</div>
Email: <input type="text" formControlName="email"/>
<div *ngIf="userForm.controls['email'].hasError('required')" style="color:mediumvioletred;">
please enter Email
</div>
<div *ngIf="userForm.controls['email'].hasError('minlength')" style="color:mediumpurple">
minimun 4 chars
</div>
<div *ngIf="userForm.controls['email'].hasError('maxlength')" style="color:navy;">
Exceeded morethan 6 letters
</div>
<div formGroupName="address">
street: <input type="text" formControlName="street"/> <br>
City: <input type="text" formControlName="city"/> <br>
PostalCode: <input type="text" formControlName="postalCode"/><br>
<div *ngIf="userForm.controls['address'].controls['postalCode'].hasError('required')" style="color:mediumvioletred;">
enter postalCode
</div>
<div *ngIf="userForm.controls['address'].controls['postalCode'].hasError('minlength')" style="color:mediumvioletred;">
minimum 4 chars
</div>
<div *ngIf="userForm.controls['address'].controls['postalCode'].hasError('maxlength')" style="color:mediumvioletred;">
maximum 6 chars
</div>
</div>
<br>
<input type="submit" value="Submitt" />
</form>
************************************************************************
'Content-type':'text/html' for response
In one screen mutiple threads.
nodeserver used to perform operations.
***********************************************************************************************
1.what is angular?
-> Its a client side javascript fw,it provides following features
Templates,Databindings,controller,services,directives,pipes
Template:
Angular uses Html as template language, every template has common html and databinds
eg: <div>{{}}</div>
Databidngs:
Contrller propertis can be bind with view(UI).These are 2 types
a.Oneway databindg b.Two way databinding
Controller:
It manages request response life cycle for template.It provides data bind and Event binding.
Services:
These are used for communicate with Server and RestApis, aswell as it contains common logic we can inject one service to multiple components.
Directives:
Used to extend the Html element features by creating our own element and attributes.
Pipes or Filters:
Used to transform the data from one formate to another formate.
wht is npm:
Npm means Node Package Manager, it is used to manage all project dependencys. It uses Package.json for dependency management.npm can be used to download these dependencies and attach them to your project
what is Module?
what is Component?
ng serve commond:
Used to compile the typescript code and convet into javascript code at the time of building.
*Dependency management:
All services configuerd as dependencys means this objects are reusable code at any where.
Angular creates only one object and inject this object whereever it is necessary.
Json method:
used to convert json object to string formate.
How to configure client side page natation?
Slice method is used to gives start and end index.
* What is diff ngIf and ngShow?
ngIf hides or shows the elements by adding or removing the element from dom.whereas ngshow uses css disply property with none value.
How to access Rest api calls?
we need to use Reactive js observables, in this we need to use map method and subscribe method.
Map:
It provides transformation logic means converting string data to json data.
Subscribe:
It is observer, we needd to subscribe the observable.It accepting 3 types of call backs, 1.Success, 2.Error,3.Complete call back.
Cross Origin Request(CORS):
while running Api and angular project we are seeing different port no.r.
Conditional display:
ngIf and ngShow
what is diff b/w angular2 and 4?
Typescript 1.8 -2
Typescript 2.2 -4
Animation -2 (angular/core)
Animation -4 (separte package)
why we dont have angular3?
Angulr 2 routing implemention is deprecated beacuse of bad design,so redesign relese as route 3 but angular framework still 2.To overcome this they straight way realsed angular4.
How to merge one component to another component?
Two ways, one is by adding selecter tag in any another componet's html template
second is by using Routing concept.
*Change Reduction (pusch):
whenever value of component changes angular revalue the expression in the current view.
In angular 1 we use watcher concept it is very big problem to maintain all watchers for a big application. To solve this prblm angular 2 uses this change Reduction concept.
How to work with Security in angular 2?
As part of login process send authenticated information to the client side stores the authenticated info into browser memory by calling localStorage.setItem(). To access autheniation info in the service layer provides one method in this method call getItem().
On logout clear the browsser memory data.
How to give port in angular 2?
ng s --open -port 4400
***********************************************************
http://www.c-sharpcorner.com/forums/call-web-api-post-method-from-angular-2-app
*************************************************************
https://tools.ietf.org/html/rfc6749#section-2.2
https://tools.ietf.org/html/rfc6749#section-2.2
https://www.c-sharpcorner.com/UploadFile/ff2f08/token-based-authentication-using-Asp-Net-web-api-owin-and-i/
https://www.moqdigital.com.au/insights/technical/12-steps-to-token-authentication-using-owin