SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
presented by
Paras Mendiratta
Session 2
Topics for Today
1. Planning App
2. Data Model
3. Component LifeCycle
4. Communication Between Components
5. Directives
6. Pipes
7. Routes
8. Services
9. Forms
2
1. Planning
Create Project
// 1. Create New Project
ng new cookbook
// 2. Go to Project Directory
cd cookbook
// 3. Add Bootstrap Library
npm install bootstrap
// 4. Add Styles in “.angular-cli.json” file
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
// 5. Run Project & open browser with URL: http://localhost:4200
ng serve
Recipe Page
Shopping List Page
Edit Recipe Page
New Recipe Page
9
Root
Header
Shopping List Recipe Book
FeatureComponent
Shopping List
Shopping List Edit
Recipe List
Recipe Item
Recipe Detail
Model
Ingredient
Recipe
Recipe Edit
Service
Recipe ServiceShoppingList Service
2. Data Model
Data Model
★ Data model is simple typescript class which binds JSON model data and provides

OOPS advantage on top of it.
Example:
export class Product {


private name: string;
protected value: string;
public game: string;

constructor(name: string) {
this.name = name;
}
getName(): string {
return this.name;
}
}
11
Recipe Model
recipe.model.ts File:
export class Recipe {
public name: string;
public description: string;
public imagePath: string;
public ingredients: Ingredient[];
// Constructor 

constructor(name:string, desc:string, imgPath:string,
ingredients:Ingredient[]) {
this.name = name;
this.description = desc;
this.imagePath = imgPath;
this.ingredients = ingredients;
}
}
12
Ingredient Model
ingredient.model.ts File:
export class Ingredient {
// Constructor 

constructor(public name:string, public amount:number) {}

}
13
2. Component
LifeCycle
Component Life Cycle
import { Component, OnInit, OnDestroy, OnChanges, AfterContentInit, AfterViewInit, SimpleChanges
 } from '@angular/core';
@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class TestComponent implements OnInit, OnDestroy, OnChanges, AfterContentInit, AfterViewInit {
    constructor() { }
    ngOnInit() {
        console.log('#ngOnInit');
    }
    ngOnDestroy(): void {
        console.log('#ngOnDestroy');
    }
    ngOnChanges(changes: SimpleChanges): void {
        console.log('#ngOnChanges');
    }
    ngAfterViewInit(): void {
        console.log('#ngAfterViewInit');
    }
    ngAfterContentInit(): void {
        console.log('#ngAfterContentInit');
    }
}
Console Output



1. #ngOnInit
2, #ngAfterContentInit
3. #ngAfterViewInit

4. #ngOnDestroy
#ngOnChanges is not called because it is called when bounded property gets
changed. Example property bound with @Input tag.
3. Communication
Between Components
Types of Communication
1. Informing changes to Peer Component
2. Informing changes to Parent Component
3. Informing changes to Child Component
How to Communicate?
Service
Layer
Used for
passing data
from parent to
child
components
Used for
informing parent
for data change
happen in Child
using Events
Allows Parent to
access Child’s
public variable
and methods
@ViewChild

Tag
Allows Parent to
access Child
Component
Public
Variables
Using 

Local
Variable
Allows
Bidirectional
Communication
@Input

Tag
@Output
Tag
@Input
export class ChildComponent {
@Input() child: Child;
@Input('master') masterName: string;
}
Child Component File:
Parent Template File:
<h2>{{master}} controls {{children.length}} Children</h2>
<app-child *ngFor="let child of children"
[child]="child"
[master]="master">
</app-child>
Alias Name for ‘masterName’
@Output
✓ The child component exposes an EventEmitter property with which it emits

events when something happens.
✓ The parent binds to that event property and reacts to those events.
export class ChildComponent {
@Output() onTouched = new EventEmitter<boolean>();
touched(agreed: boolean) {
this.onTouched.emit(agreed);
}
}
Child Component File:
<button (click)="touched(true)">Agree</button>
<button (click)="touched(false)">Disagree</button>
Child Template File:
@Output
export class ParentComponent {
onTouched(agreed: boolean) {
console.log(“Agreed:”, agreed);
}
}
Parent Component File:
<app-child (onTouched)=“onTouched($event)”></app-child>
Parent Template File:
Using Local Variable
✓ A parent cannot directly access the child component. However, if assign a local

variable to child component tag then we can access its public variables.
✓ To define a local variable we use hash (#) tag.
✓ It is simple and easy to use.
✓ It has drawback that all parent-child wiring has to be done on parent side only.
<div>{{agreed}}</button>
<app-child #agreed></app-child>
Parent Template File:
@ViewChild
✓ When parent need to access the methods of child or wants to alter the variables

of child component then @ViewChild is useful.
Parent Component File:
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent);

private childComponent: ChildComponent;



ngAfterViewInit() {
console.log(“Current State: ”, this.childComponent.getState());
}

}
Using Services
✓ Services support bidirectional communication within the family.
✓ We use observer-observable design pattern to achieve this.
Component A
Button A
Component B
Button B
dataAcopy, dataB,
dataCcopy
dataA, dataBcopy,
dataCcopy
Component C
Button C
dataAcopy, dataBcopy,
dataC
Objective: Updates the value of A, B, C in all components when 

Button A, Button B, or Button C presses respectively.
Assignm
ent
5. Directives
1. Component Level - directives with template

<app-child></app-child>
2. Structural Level - helps in changing DOM Layout

<div *ngIf="isValid;then content else other_content">

here is ignored

</div>



<ng-template #content>content here...</ng-template>

<ng-template #other_content>other content here...</ng-template>
3. Attribute Level - Changes the appearance or behaviour of the
component
“Modifies DOM elements and/or extend their behaviour”
Directives
Attribute Directive
import { Directive, ElementRef, Input } from ‘@angular/core’;
@Directive({
selector: [‘app-background’]
})
export class BackgroundDirective {
@Input(‘app-background’) backgroundValue: string;



constructor(private el: ElementRef) {}
ngOnInit() {
this.setBackgroundColor(this.backgroundValue);
}
setBackgroundColor(value:string) {
this.el.nativeElement.style.background = value;
}
}
Background Colour Modifier
Using Attribute Directive
// Example: Background Colour Modifier

<div app-background=“green”>This is with green colour background.</div>
<div app-background=“pink”>This is with pink colour background.</div>
<div app-background=“seagreen”>This is with ‘sea green’ colour background.</div>
6. Pipes
“Pipe transform displayed values within a template.”
Pipes
Pipe Example
// Here birthday is date object and pipe prints birthday in format of
// “MM/DD/YY”
<div> Ram’s birthday comes on {{ birthday | date:“MM/dd/yy” }} </div>
// Prints Name of product in UPPERCASE letters
<div> Ram’s birthday comes on {{ productName | uppercase }} </div>
// Prints Name of product in LOWERCASE letters
<div> Ram’s birthday comes on {{ productName | lowercase }} </div>
Custom Pipe
exponential-strength.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent: string): number {
let exp = parseFloat(exponent);
return Math.pow(value, isNaN(exp) ? 1 : exp);
}
}
ComponentA.template.html

<h2>Power Booster</h2>
<p>Super power boost: {{2 | exponentialStrength: 10}}</p>
7. Routes
Route Example
const appRoutes: Routes = [
{ path: ‘home’, redirectTo:‘/’, pathMatch: ‘full’},
{ path: ‘users’, component: UserComponent, children:[
{ path: ‘’, component: NoUserComponent },
{ path: ‘new’, component: UserEditComponent },
{ path: ‘:id’, component: UserProfileComponent },
{ path: ‘:id/edit’, component: UserEditComponent }],
{ path: ‘game-list’, component: GameListComponent },
{ path: ‘’, component: HomeComponent }
];

Integrating Route
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from ‘@angular/platform-browser';
import { Routes, RouterModule } from ‘@angular/router‘;
import { AppComponent } from ‘./app.component';
@NgModule({
imports: [ BrowserModule, RouterModule.forRoot(appRoutes) ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Route Tags
<router-outlet></router-outlet>
<!-- Routed views go here -->
<!—— Router Link Example ——>
<a routerLink=“/home”>Home</a>
<!—— Currently active link ——>
<a routerLink=“/users” routerLinkActive=“active”>Users</a>
8. Services
Service
“ Responsible for arranging data for view components. ”
★ Services are injectable.
★ A service provided in a component, can be reused by its children.
★ Normally, we keep business logics in services.
★ Services can be used:-
- For fetching data from server
- For fetching data from LocalStorage or SessionStorage
★ Service can be used for passing data from one component to any other
component.
★ Service can be used to inform change in data in one component to
another component who is observing the data.
We never create instance of service. It is created by Angular.
40
Service Example
Example:
import { Injectable } from ‘@angular/core’;
import { Product } from ‘./product.model’;
import { PriceService } from ‘./price.service’;
@Injectable()
export class ProductService {
private products: Product[] = [
new Product(‘Product #A’, ‘Plier’),
new Product(‘Product #B’, ‘Wrench’)
];
constructor(private priceService: PriceService) { }
getProduct(index: number): Promise<Product> {
return Promise.resolve(this.products[index]);
}
}
41
8. Forms
Forms
Template
Driven
Reactive
Forms
43
Easy to Use
Suitable for simple scenarios
Similar to Angular 1.x
Two way data binding (NgModel)
Minimal component code
Automatic track of form & its data
Unit testing is another challenge
Flexible but needs lot of practice
Handles any complex scenarios
Introduce in Angular 2
No data binding is done
More code in Component over HTML
Data tracked via events & dynamically
added elements
Easier Unit Testing
Wrapping up
✓ Planning Angular App
✓ Component LifeCycle
✓ Communication between components
✓ Routes
✓ Directives
Next Session
๏ User Authentication
๏ Consuming HTTP API
๏ Integrating with Firebase
๏ Production Deployment
44
Topics Covered
✓ Routes
✓ Data Model
✓ Services
✓ Forms
✓ Pipes
Thank You

Mais conteúdo relacionado

Mais procurados

Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend DevelopersSergio Nakamura
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with VaadinPeter Lehto
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsRapidValue
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Jeado Ko
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for MagentoIvan Chepurnyi
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...Katy Slemon
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xAndolasoft Inc
 

Mais procurados (20)

Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with Vaadin
 
Angular js
Angular jsAngular js
Angular js
 
React outbox
React outboxReact outbox
React outbox
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 
Angular JS
Angular JSAngular JS
Angular JS
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Speed up your GWT coding with gQuery
Speed up your GWT coding with gQuerySpeed up your GWT coding with gQuery
Speed up your GWT coding with gQuery
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
How to Implement Basic Angular Routing and Nested Routing With Params in Angu...
 
Angularjs
AngularjsAngularjs
Angularjs
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
 
Web 5 | JavaScript Events
Web 5 | JavaScript EventsWeb 5 | JavaScript Events
Web 5 | JavaScript Events
 

Semelhante a Angular JS2 Training Session #2

Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web ComponentsMateus Ortiz
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next FrameworkCommit University
 
Peggy angular 2 in meteor
Peggy   angular 2 in meteorPeggy   angular 2 in meteor
Peggy angular 2 in meteorLearningTech
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinSimon Gauvin
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!David Gibbons
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexChristoffer Noring
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in AngularYadong Xie
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedGil Fink
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesDavid Giard
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slidesDavid Barreto
 

Semelhante a Angular JS2 Training Session #2 (20)

Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
Desbravando Web Components
Desbravando Web ComponentsDesbravando Web Components
Desbravando Web Components
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Peggy angular 2 in meteor
Peggy   angular 2 in meteorPeggy   angular 2 in meteor
Peggy angular 2 in meteor
 
Introduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon GauvinIntroduction to Polymer and Firebase - Simon Gauvin
Introduction to Polymer and Firebase - Simon Gauvin
 
AngularDart - Meetup 15/03/2017
AngularDart - Meetup 15/03/2017AngularDart - Meetup 15/03/2017
AngularDart - Meetup 15/03/2017
 
mean stack
mean stackmean stack
mean stack
 
Django crush course
Django crush course Django crush course
Django crush course
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
How to Webpack your Django!
How to Webpack your Django!How to Webpack your Django!
How to Webpack your Django!
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
 
Hidden Docs in Angular
Hidden Docs in AngularHidden Docs in Angular
Hidden Docs in Angular
 
Stencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrivedStencil the time for vanilla web components has arrived
Stencil the time for vanilla web components has arrived
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 
Angular performance slides
Angular performance slidesAngular performance slides
Angular performance slides
 

Último

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 

Último (20)

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 

Angular JS2 Training Session #2

  • 2. Topics for Today 1. Planning App 2. Data Model 3. Component LifeCycle 4. Communication Between Components 5. Directives 6. Pipes 7. Routes 8. Services 9. Forms 2
  • 4. Create Project // 1. Create New Project ng new cookbook // 2. Go to Project Directory cd cookbook // 3. Add Bootstrap Library npm install bootstrap // 4. Add Styles in “.angular-cli.json” file "../node_modules/bootstrap/dist/css/bootstrap.min.css" // 5. Run Project & open browser with URL: http://localhost:4200 ng serve
  • 9. 9 Root Header Shopping List Recipe Book FeatureComponent Shopping List Shopping List Edit Recipe List Recipe Item Recipe Detail Model Ingredient Recipe Recipe Edit Service Recipe ServiceShoppingList Service
  • 11. Data Model ★ Data model is simple typescript class which binds JSON model data and provides
 OOPS advantage on top of it. Example: export class Product { 
 private name: string; protected value: string; public game: string;
 constructor(name: string) { this.name = name; } getName(): string { return this.name; } } 11
  • 12. Recipe Model recipe.model.ts File: export class Recipe { public name: string; public description: string; public imagePath: string; public ingredients: Ingredient[]; // Constructor 
 constructor(name:string, desc:string, imgPath:string, ingredients:Ingredient[]) { this.name = name; this.description = desc; this.imagePath = imgPath; this.ingredients = ingredients; } } 12
  • 13. Ingredient Model ingredient.model.ts File: export class Ingredient { // Constructor 
 constructor(public name:string, public amount:number) {}
 } 13
  • 16. import { Component, OnInit, OnDestroy, OnChanges, AfterContentInit, AfterViewInit, SimpleChanges  } from '@angular/core'; @Component({     selector: 'app-shopping-edit',     templateUrl: './shopping-edit.component.html',     styleUrls: ['./shopping-edit.component.css'] }) export class TestComponent implements OnInit, OnDestroy, OnChanges, AfterContentInit, AfterViewInit {     constructor() { }     ngOnInit() {         console.log('#ngOnInit');     }     ngOnDestroy(): void {         console.log('#ngOnDestroy');     }     ngOnChanges(changes: SimpleChanges): void {         console.log('#ngOnChanges');     }     ngAfterViewInit(): void {         console.log('#ngAfterViewInit');     }     ngAfterContentInit(): void {         console.log('#ngAfterContentInit');     } } Console Output
 
 1. #ngOnInit 2, #ngAfterContentInit 3. #ngAfterViewInit
 4. #ngOnDestroy #ngOnChanges is not called because it is called when bounded property gets changed. Example property bound with @Input tag.
  • 18. Types of Communication 1. Informing changes to Peer Component 2. Informing changes to Parent Component 3. Informing changes to Child Component
  • 19. How to Communicate? Service Layer Used for passing data from parent to child components Used for informing parent for data change happen in Child using Events Allows Parent to access Child’s public variable and methods @ViewChild
 Tag Allows Parent to access Child Component Public Variables Using 
 Local Variable Allows Bidirectional Communication @Input
 Tag @Output Tag
  • 20. @Input export class ChildComponent { @Input() child: Child; @Input('master') masterName: string; } Child Component File: Parent Template File: <h2>{{master}} controls {{children.length}} Children</h2> <app-child *ngFor="let child of children" [child]="child" [master]="master"> </app-child> Alias Name for ‘masterName’
  • 21. @Output ✓ The child component exposes an EventEmitter property with which it emits
 events when something happens. ✓ The parent binds to that event property and reacts to those events. export class ChildComponent { @Output() onTouched = new EventEmitter<boolean>(); touched(agreed: boolean) { this.onTouched.emit(agreed); } } Child Component File: <button (click)="touched(true)">Agree</button> <button (click)="touched(false)">Disagree</button> Child Template File:
  • 22. @Output export class ParentComponent { onTouched(agreed: boolean) { console.log(“Agreed:”, agreed); } } Parent Component File: <app-child (onTouched)=“onTouched($event)”></app-child> Parent Template File:
  • 23. Using Local Variable ✓ A parent cannot directly access the child component. However, if assign a local
 variable to child component tag then we can access its public variables. ✓ To define a local variable we use hash (#) tag. ✓ It is simple and easy to use. ✓ It has drawback that all parent-child wiring has to be done on parent side only. <div>{{agreed}}</button> <app-child #agreed></app-child> Parent Template File:
  • 24. @ViewChild ✓ When parent need to access the methods of child or wants to alter the variables
 of child component then @ViewChild is useful. Parent Component File: export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent);
 private childComponent: ChildComponent;
 
 ngAfterViewInit() { console.log(“Current State: ”, this.childComponent.getState()); }
 }
  • 25. Using Services ✓ Services support bidirectional communication within the family. ✓ We use observer-observable design pattern to achieve this.
  • 26. Component A Button A Component B Button B dataAcopy, dataB, dataCcopy dataA, dataBcopy, dataCcopy Component C Button C dataAcopy, dataBcopy, dataC Objective: Updates the value of A, B, C in all components when 
 Button A, Button B, or Button C presses respectively. Assignm ent
  • 28. 1. Component Level - directives with template
 <app-child></app-child> 2. Structural Level - helps in changing DOM Layout
 <div *ngIf="isValid;then content else other_content">
 here is ignored
 </div>
 
 <ng-template #content>content here...</ng-template>
 <ng-template #other_content>other content here...</ng-template> 3. Attribute Level - Changes the appearance or behaviour of the component “Modifies DOM elements and/or extend their behaviour” Directives
  • 29. Attribute Directive import { Directive, ElementRef, Input } from ‘@angular/core’; @Directive({ selector: [‘app-background’] }) export class BackgroundDirective { @Input(‘app-background’) backgroundValue: string;
 
 constructor(private el: ElementRef) {} ngOnInit() { this.setBackgroundColor(this.backgroundValue); } setBackgroundColor(value:string) { this.el.nativeElement.style.background = value; } } Background Colour Modifier
  • 30. Using Attribute Directive // Example: Background Colour Modifier
 <div app-background=“green”>This is with green colour background.</div> <div app-background=“pink”>This is with pink colour background.</div> <div app-background=“seagreen”>This is with ‘sea green’ colour background.</div>
  • 32. “Pipe transform displayed values within a template.” Pipes
  • 33. Pipe Example // Here birthday is date object and pipe prints birthday in format of // “MM/DD/YY” <div> Ram’s birthday comes on {{ birthday | date:“MM/dd/yy” }} </div> // Prints Name of product in UPPERCASE letters <div> Ram’s birthday comes on {{ productName | uppercase }} </div> // Prints Name of product in LOWERCASE letters <div> Ram’s birthday comes on {{ productName | lowercase }} </div>
  • 34. Custom Pipe exponential-strength.pipe.ts
 import { Pipe, PipeTransform } from '@angular/core'; @Pipe({name: 'exponentialStrength'}) export class ExponentialStrengthPipe implements PipeTransform { transform(value: number, exponent: string): number { let exp = parseFloat(exponent); return Math.pow(value, isNaN(exp) ? 1 : exp); } } ComponentA.template.html
 <h2>Power Booster</h2> <p>Super power boost: {{2 | exponentialStrength: 10}}</p>
  • 36. Route Example const appRoutes: Routes = [ { path: ‘home’, redirectTo:‘/’, pathMatch: ‘full’}, { path: ‘users’, component: UserComponent, children:[ { path: ‘’, component: NoUserComponent }, { path: ‘new’, component: UserEditComponent }, { path: ‘:id’, component: UserProfileComponent }, { path: ‘:id/edit’, component: UserEditComponent }], { path: ‘game-list’, component: GameListComponent }, { path: ‘’, component: HomeComponent } ];

  • 37. Integrating Route app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from ‘@angular/platform-browser'; import { Routes, RouterModule } from ‘@angular/router‘; import { AppComponent } from ‘./app.component'; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(appRoutes) ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }

  • 38. Route Tags <router-outlet></router-outlet> <!-- Routed views go here --> <!—— Router Link Example ——> <a routerLink=“/home”>Home</a> <!—— Currently active link ——> <a routerLink=“/users” routerLinkActive=“active”>Users</a>
  • 40. Service “ Responsible for arranging data for view components. ” ★ Services are injectable. ★ A service provided in a component, can be reused by its children. ★ Normally, we keep business logics in services. ★ Services can be used:- - For fetching data from server - For fetching data from LocalStorage or SessionStorage ★ Service can be used for passing data from one component to any other component. ★ Service can be used to inform change in data in one component to another component who is observing the data. We never create instance of service. It is created by Angular. 40
  • 41. Service Example Example: import { Injectable } from ‘@angular/core’; import { Product } from ‘./product.model’; import { PriceService } from ‘./price.service’; @Injectable() export class ProductService { private products: Product[] = [ new Product(‘Product #A’, ‘Plier’), new Product(‘Product #B’, ‘Wrench’) ]; constructor(private priceService: PriceService) { } getProduct(index: number): Promise<Product> { return Promise.resolve(this.products[index]); } } 41
  • 43. Forms Template Driven Reactive Forms 43 Easy to Use Suitable for simple scenarios Similar to Angular 1.x Two way data binding (NgModel) Minimal component code Automatic track of form & its data Unit testing is another challenge Flexible but needs lot of practice Handles any complex scenarios Introduce in Angular 2 No data binding is done More code in Component over HTML Data tracked via events & dynamically added elements Easier Unit Testing
  • 44. Wrapping up ✓ Planning Angular App ✓ Component LifeCycle ✓ Communication between components ✓ Routes ✓ Directives Next Session ๏ User Authentication ๏ Consuming HTTP API ๏ Integrating with Firebase ๏ Production Deployment 44 Topics Covered ✓ Routes ✓ Data Model ✓ Services ✓ Forms ✓ Pipes